texts: Entry Form doesn't save the entry and goes to 404 page

texts:
I have a frontend Entry Form that will not save an entry and goes to a 404 page.

Basically i have this:

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data" class="add-a-resource__form">
{{ getCsrfInput() }}
<input type="hidden" name="action" value="entries/saveEntry">
<input type="hidden" name="redirect" value="/resources/thank-you">
<input type="hidden" name="sectionId" value="4">
<input type="hidden" name="enabled" value="1">
<input type="hidden" name="typeId" value="4">
<input type="hidden" name="fields[topContent]" value="test">
</form>

And in the log in the session array i have:

'9df612913c35fa7bdbde58405537f412__timeout' => 1479139200,
  '9df612913c35fa7bdbde58405537f412Yii.CWebUser.flash.error' => 'Couldn’t save entry.',
  '9df612913c35fa7bdbde58405537f412Yii.CWebUser.flashcounters' =>
  array (
    'error' => 0,
  ),

I am logged in as an admin so have permission to write to the channel, the details are right in the hidden fields, but when i submit the form, it goes to a 404 page no matter what i put in the redirect input.

Any ideas?


texts: Find All Levels of Subfolders under Assets

texts:
I'm working with images in subfolders, several levels deep, under the Assets parent folder.

-Assets
--Dept_A
---Jan15
--Dept_B
---Jan15
---Jan16

I've come across this code (below), but it only will find the parent ("Assets") and the children ("Dept_A" and "Dept_B").
I want to loop through all of the subfolders, if possible.  Thanks for any leads.

foreach ($assetSources as $source)
    {
        $folder = craft()->assets->findFolder(array(
            'sourceId' => $source->id,
            'parentId' => ':empty:'
        ));

        $subfolders = craft()->assets->findFolders(array(
            'parentId' => $folder->id
        ));

        $foldersBySource[$source->id] = $folder;
        $subfoldersBySource[$source->id] = $subfolders;
    }


texts: Skipping the shipping part for custom virtual product

texts:
We've a WIP that need virtual products. Not the official plugin, but a custom product type that don’t required any shipping. I was wondering if anyone ever try to do so, and how.

I was thinking about a Switch Field for that particular Product Type that will affect all the checkout process (if no product need shipping in the order, of course) : don't show the "Shipping Address" form, skip the Shipping Method choice and hide any shipping mentions on the order and emails.

Note: I already have a custom module to do custom actions on event for this product type. Extend Craft Commerce is a possibility.


texts: How do I target the first item in a Twig for loop?

texts:
I'm looping through some images and want to target just the first image. How do I do that?

{% for image in entry.images %}
<img src="{{ image.url }}" alt="{{ image.title }}">
{% endfor %}


texts: Showing entries in same category, excluding the current entry

texts:
I'm new to this, so sorry if this is really basic.

I want to display a list of entries in the same category as the main entry in my template, excluding the current entry.

This is my code:

{% for category in entry.tutorialCategory.all() %}
{% for tutorial in craft.entries
   .section('tutorials')
   .relatedTo(category).all()
   .id('not ' ~ entry.id) %}
       {{ tutorial.title }}
{% else %}
       There are currently no related tutorials.
{% endfor %}
{% endfor %}

I always get the 'There are currently no related tutorials.' message though.

Any suggestions on where I'm going wrong?


texts: Prevent Redactor from stripping tags like

texts:
Is there any possible way to prevent <span> tags from being stripped from a Redactor field? I've tried all I can using custom Redactor and HTMLPurifier configs to no avail.

Basically what I'm trying to do long-term is replace heading tags like <h2> and <h3> with <span>  and then apply the same styling as the heading tags, perhaps by applying classes to the <span>s and going from there.

Things I've tried to no avail:

Added "allowedTags" rule to Redactor config
Added "HTML.Allowed" rule to HTML Purifier config
Disabled HTML Purfier for field altogether
Added "paragraphize": false to Redactor config

The only resource I've found regarding this is this question from 3 years ago. Haven't had any luck with those suggestions either.
Thanks in advance!


texts: Using the custom styled Stripe button with Craft Commerce

texts:
I know there is the Stripe checkout button that is in the example docs but I would like more control over how things look and work.

I guess this is where it's over to me to look at the Stripe docs:

Styled Custom Button

It's difficult to work out what exactly is required in order to send all the details Stripe requires and then process the response giving Craft Commerce everything it needs. Then send the user to an order complete screen.

I have the custom button sort of working using:

<form method="POST">
  <input type="hidden" name="action" value="commerce/cart/updateCart">

  <button id="paymentButton" class="button is-primary">Purchase</button>

  <script>
    var handler = StripeCheckout.configure({
      key: '{{ cart.paymentMethod.settings.publishableKey ?? '' }}',
      image: '/assets/img/tfa-logo-128.png',
      locale: 'auto',
      token: function(token) {
        // You can access the token ID with `token.id`.
        // Get the token ID to your server-side code for use.
      }
    });

    document.getElementById('paymentButton').addEventListener('click', function(evt) {
      // Open Checkout with further options:
      handler.open({
        name: '{{ siteName }}',
        email: '{{ cart.email }}',
        currency: '{{ cart.paymentCurrency }}',
        description: 'Membership',
        zipCode: true,
        amount: {{ cart.totalPrice|commerceCurrency(cart.paymentCurrency,convert=true,format=false) * 100 }}
      });
      evt.preventDefault();
    });

    // Close Checkout on page navigation:
    window.addEventListener('popstate', function() {
      handler.close();
    });
  </script>
</form>

This looks to work but doesn't send a charge to Stripe or save in the commerce plugin (it just sits as an active cart). I guess this is down to the token not being set but how do you do that?


texts: Minor math in template, display result before logic in DOM

texts: Currently I’m looping through some results on an athlete’s bio page to get their individual win/loss record… Something like {% if matchWon is defined %}{% set wins = wins + 1 %}{% endif %} is looping in a table of their records. This works great, and will accumulate their record just fine, but what if I want to show the athlete’s record *before* the table where all that logic is run? Any way to display those final win/loss values out earlier in the dom?


texts: How would I show a message and define where the user is redirected after changing their email through a front end form?

texts:
I have a profile form where a user can update their email.

Upon doing so I would like to:

Show the user a message saying they must check their email to verify the new email address.
After they click the "Verify Email" address in their inbox, redirect them to a url preferably with a Flash Message letting them know they'e successfully updated their email.

Possible?


texts: Is there any way or plugin to implement Cloudways CDN with Craft?


texts: How can I make a template output its own filename?

texts: Is it possible to output the template name being used? Using a global variable or something similar? I am wanting to check which template is being used in a conditional.


texts: Show related entries without current entry

texts:
I'm trying to show related entries to current entry by tag ID (which is working fine) but getting hung up when trying to exclude the current entry from the loop. I think I'm having an issue with paginate tags requiring an element criteria model but I'm not able to figure out how to get around this.

{% set segment = craft.request.lastSegment %}
{% for entries in craft.entries.slug(segment) %}
  {% set current = craft.entries.slug(segment) %}
  {% set tagId = entry.myTagFieldHandle.first() %}
  {% set suite = craft.entries.relatedTo(tagId) %}

    {% paginate suite|without(current) as entries %}
      {% for entry in entries %}
        {{ entry.title }}
      {% endfor %}
    {% endpaginate %}

{% endfor %}

Excluding the without filter on paginate outputs everything fine, but includes the current entry. I know there are probably better ways of doing this and I appreciate any help, thanks!


texts: Does Craft Commerce support multi-currency?

texts: After looking at the Features page for Craft Commerce, I didn't see anything regarding multi-currency support. Is this something that's available for certain payment processors?


texts: Calling unknown method: craft\models\Section::hasUrls() - Craft 3 upgrade

texts:
I am migrating a site from Craft 2 - Craft 3. In my sitemap template I have the following code;

{% for section in craft.sections.getAllSections() %}
  {# We only care about sections that have URLs #}
  {% if section.hasUrls %}

{{ section.name }}

        {# Loop through each of its entries #}
        {% for entry in craft.entries.sectionId(section.id).limit(null) %}

{{ entry.title }}

        {% endfor %}

  {% endif %}
{% endfor %}

I am getting the error Calling unknown method: craft\models\Section::hasUrls()

I cannot find the equivalent or updated value in the Craft 3 docs. Can anyone advise as to how this should be rewritten or what I should use instead of if section.hasUrls in Craft 3?


texts: Entries field: Output entries related to category

texts:
I have an entries field (activityPicker) that links to other entries in a different section. These other entries have categories (things-to-do and things-to-eat), and I'm trying to figure out how to filter these entries by categories.

My first instinct was to do something similar to this:

{# Categories #}
{% set CatToDo = craft.categories.slug('things-to-do') %}
{% set CatToEat = craft.categories.slug('things-to-eat') %}

{# Entries #}
{% set toDo = entry.activityPicker.relatedTo(catToDo) %}
{% set toEat = entry.activityPicker.relatedTo(catToEat) %}

{# Output #}
{% for item in toDo %}
   {{ item }}
{% endfor %}

{% for item in toEat %}
   {{ item }}
{% endfor %}

however that didn't work so I tried playing with targetElement and sourceElement in the relatedTo parameter:

{% set toEat = entry.activityPicker.relatedTo({
   targetElement: catToEat
}) %}

[...]

but this still doesn't work. Basically I get that entry.activityPicker returns an array of posts, but I haven't figured out how to filter those posts in a meaningful way before they hit the template.


texts: Nested Matrix functionality for one block type using Tags

texts:
I have an entry with two matrix fields and I want to use relations between them using Tags to create a fake nested Matrix functionality for one block type. The "main" matrix field is for creating a typical banded page (several horisontal stripes of content). One of the blocks in this main matrix has to contain a contentSlider, and since in this specific case adding an Assets field is not sufficient we have to nest or merge two matrix fields.

While looping through the main matrix field using the Switch method I have a block type named "contentSlider". In this block type I have a Tags field named "showTags". In my second matrix field named "slidesMatrix" I have a field named "tags". I want to find blocks in the second matrix (slidesMatrix) related to the current block in the main matrix.

Here is my attempt, it is not giving me any errors but it is not outputting the "slide.heading" field either so something must be wrong:

{% case "contentSlider" %}
    {% set tagsToFind = block.showTags %}
    {% set relatedSlides = entry.slidesMatrix.tags.relatedTo(tagsToFind).order('score').find() %}
    {% for slide in relatedSlides %}
        Matched Tag in: {{ slide.heading }}

    {% endfor %}

This alternative code works, but it is only matching the first Tag from the current block to all the Tags in the second matrix block (slidesMatrix.tags) and switching to one of the native Craft methods like "relatedTo" would be a more powerful solution.

{% case "contentSlider" %}
    {% set tagsToFind = block.showTags %}
    {% set tagToFind = tagsToFind.first.title %}
    {% for slide in entry.slidesMatrix if tagToFind in slide.tags %}
        Matched Tag in: {{ slide.heading }}

    {% endfor %}

To sum this up into one question;
How can I loop through a matrix field filtered by Tags contained in a tags fields inside the matrix blocks I want to loop through, using a native Craft feature like 'relatedTo'?


texts:
Background... I took a look at this post answered by @Damon

My objective is similar.  I have a channel for news.  Each entry in news is assigned various categories (e.g. product category).

I do not have a "single" in Craft for each product category.  However, I do have a _productCategory.html template.  And each product category has its own page. ...that is, productCategory/{slug} with {slug} being an individual product category.   And I have a link to each product category in my nav.   I know, pretty basic.

I know there are multiple ways to skin the cat, but am I missing out on anything by not using a single for each product category page?  Is there any impact on SEO?


texts:
I want to have an asset field which only allows .svgs.
To be more specific, I want to upload icons I can later import in my templates via the svg() command. Is this possible without any plugins or a custom field?


texts: On Craft Client, what does the client account get?

texts:
A definitive description of the client account would be useful for this. What does a client account get? For example, can they clear the cache?

I know I can login and find this out myself, but it would be helpful to have a go-to article on this for future reference.


texts:
I've just set up an S3 bucket and have a transform in my template. Should these transformed images be saved on S3? It doesn't look like they are, however my template is pulling out an S3 URL:

When using a base image at http://s3-eu-west-1.amazonaws.com/rallyagency/princess-leia-princess-leia-walking-in-new-york-is-just-plain-awesome.jpeg, my template outputs this:

Note the addition of the directory _200x200_crop_center-center_75 in the path - that doesn't exist on the S3 bucket.


texts: Mcrypt is required on OS X Mavericks 10.9.4

texts:
I'm stuck on the /admin/install page, getting an error "Can't run Craft :(" saying that Mcrypt is required.

I've tried installing with Homebrew, but kept getting an error. So, I installed mcrypt manually using these instructions on Stack Overflow. PHP and Mcrypt are installed:

$ which php
/usr/local/bin/php

$ which mcrypt
/usr/local/bin/mcrypt

And in my php.ini file I've added:

extension=mcrypt.so

(I've also tried including the path extension=/usr/local/bin/mcrypt.so)

In the ;extension area (around line 880).

Even after restarting Apache, I still get the same error that "Mcrypt isn't installed" from Craft.


texts: Freeform plugin conditional rules not working

texts:
I have 3 select fields in my form - Select A, Select B and Select C. I want Select B & C to be hidden by default. If Select A option is not X, then show Select B. If option Y is not selected in Select B field then show Select C.
This is what the conditional rule on the form looks like.

Note that Type of Loan is Select A, while What to know about this loan is Select B.
Am I doing anything wrong here? Cos this rule isn't working. I am using version 3.8.4


texts: Commerce Mollie - Duplicate transactions

texts:
I'm using the Mollie gateway for Craft Commerce and sometimes an order recieves multiple transactions. The order shows two transactions with pretty much the same information but a different transaction hash. The order then shows as overpaid but the money is only recieved once.
I'm thinking that Commerce is either receiving too many webhooks or an unhandled status update is defaulting to paid resulting in a fake transaction. Not sure if its a Commerce bug, it might be. Does anyone know what could be causing this?
Thanks in advance!


texts: How to add addition attribute and fields in public registration form in Craft CMS

texts:
User Registration Form

I want to setup a public registration form in Craft CMS.  Currently this form support only fields username, email, password, but I want to add at least 10 other fields.

Also I want to create three types of user groups. How do I update the group in the public registration form?

User registration in Craft


texts: Why is using the cache tag more expensive than outputting static text?

texts:
The Craft docs have a good overview of the {% cache %} tag.

The docs give a couple examples of when not to use the {% cache %} tag.  In particular, they give this example:

Don’t use them to cache static text; that will be more expensive than simply outputting the text.

Can someone explain to me the logic behind this statement? How do the two scenarios play out where caching static text is slower than just outputting it?

Additionally, what if you are caching a page with several queries that includes static text?  Does it follow that you'll want to cache the queries in and of themselves and let the static text remain uncached?


texts: Does Craft parse requests inside a conditional if it is false?

texts:
Does Craft parse the contents of a false/negative/empty conditional statement? So would you take a performance hit if you had a big chunk of code inside a conditonal that was false?

{% set foo = "foo" %}
{% if foo == foo %}Small code {% else %} MASSIVE CODE{% endif %}


texts: How to avoid "Double-instantiating a pane on an element"

texts:
Without going into too much detail, I have a plugin where I'm trying to manage two different sets of tabs with some custom javascript. When the object initializes, I need to add a pane from the page layout to the object. Something like:

this.$pane = new Craft.Pane($(".pane"));

That line of code kinda works. However, when the page loads the console reports:

Double-instantiating a pane on an element

If I remove the above line of code this.$pane = new Craft.Pane($(".pane"));, the console log message goes away. With the line of code some things work. Without the line of code other things work. I need all the things to work at the same time.

I'm struggling to know the right question to ask, so please point me in the right direction if I am off the mark. Is it possible to check if there is an existing Craft.Pane object that exists before I try to create a new Craft.Pane object?


texts: Asset with related entry field in Matrix block

texts:
I have an Asset source "Image link gallery" with two custom fields for each Asset: "image title" (text field) & "Image link" (Entries field - can link to multiple sources).

I have a Matrix block "Image link Gallery" with an Assets field "Images" which selects from this Asset source.

I want to be be able to select a bunch of images and return the image, title, and link to the entry.

{% for imageItem in block.images %}

        {{ imageItem.imageTitle }}

{% endfor %}

This is returning all the images and titles but no links.

Where am I going wrong?


texts: Connect to an external database from a Craft 2.x plugin

texts:
I recently saw a very helpful post about how to connect to an external database from a Craft plugin and I wanted to confirm I understood the implementation correctly.

On this response the author recommended a way to leverage Yii's Query Builder on external databases. Is the following snippet the way to properly implement this in a service? Do I need to manually "close" this connection or is this alone the way to implement this?

<?php

// Connect to an external database
$db = Craft::createComponent([
    'emulatePrepare'    => true,
    'charset'           => 'utf8',
    'class'             => 'Craft\DbConnection',
    'autoConnect'       => true,
]);

$db->connectionString = 'mysql:host=localhost;dbname=MY_DB;port=3306';
$db->username = 'UN';
$db->password = 'PW';

// Use Query Builder to fetch data from the database
$data = $db->createCommand()
    ->select("*")
    ->from("TBL")
    ->queryAll();

// Pass along the data to be used in a template via variables
return $data;


texts: Get custom field value on entries.onBeforeSaveEntry event

texts:
I am trying to get a custom field value on entries.onBeforeSaveEntry, event.  So I can perform some action depending on the value of that field.

craft()->on('entries.onBeforeSaveEntry', function(Event $event)
{
    $entry = $event->params['entry'];
    $entry->publishOnMobileApp;  //publishOnMobileApp is the field handle
});

Now this line.

$entry->publishOnMobileApp;

Returns

Craft\MultiOptionsFieldData Object (
    [_options:Craft\MultiOptionsFieldData:private] =>
Array ( [0] => Craft\OptionData Object
(
    [label] => Yes [value] => yes [selected] => )
)
   [storage:ArrayObject:private] =&gt; Array()
)

I am not sure how exactly I can access just the value of the field (which is "yes" in this case) so I can perform a check.


texts: Creating customer records and saving cards during Stripe checkout?

texts:
My client is looking to, on occasion, assign a recurring Stripe plan to a one-time donor (most donations on this site are one-time). The best way to do this would be to create a customer in Stripe (and save the card token for that customer) on every transaction, so that it would  be a quick and easy process for them to find the customer and assign them a plan without needing to collect any further information from them.

Currently the Stripe plugin doesn't save anything, it simply creates a simple one-time charge.

Is it possible to use existing actions in the Stripe gateway for Commerce 2 to create customers w/ saved sources during checkout?


texts: My Entry URL Format needs are too long for the field restrictions

texts:
I'm trying to set the URL of my product entry's to be dynamically created based on 3 category fields and 2 number fields. The category fields are required, but I need to add some logic for the number fields.

It's all taking up so much space that upon saving the section's settings, the URL Format field cuts off some of my code. I'm sure there is a great reason that this field has a character limit so is there anything else I can do? I tried importing a macro, but couldn't get that to work. Do I have to create a plugin?

This is the content I need to use in my Entry URL Format that is too long with my variable names:

some-text-here/{%if object.mfgCategory.first.slug=="1hack"%}hack{%else%}{mfgCategory.first.slug}{%endif%}-{%for c in object.series%}{c.slug}-{%endfor%}{sizeCategory.first.slug}-{%if object.num1=='0'%}00{%else%}{number1}{%endif%}-{%if object.number2=='0'%}00{%else%}{number2}{%endif%}


texts: "Page not found. What’s worse, a hilarious 404 page can’t be found either."

texts:
My file structure is:

User/me/www/Craft-2.3.2644/

I am using MAMP and MAMP Points to this folder as my 'server root'.

Everything inside and including my web root has 777 permissions.

Inside this folder are three items:

craft/
public/
readme.txt

I have a MySQL database:

Domain: localhost
User: root

I have pointed the db.php file to my server, with 'root' as the password.

My index.php file in my public folder points to ../craft which reroutes to /app/index.php (a file that does exist in that location).

The most positive result I can get when surfing to localhost/public/index.php is a message that reads as below...

  Page not found

  What’s worse, a hilarious 404 page can’t be found either.

With any other permissions I cannot access the folder because I'm not allowed (oops message).

And with any other mapping in the index file I receive a message:

  File not found


texts:
I have a form to sign up for a trial (offline product) and I feel like the most logical place to store that data is Users, but requiring a password on sign up will likely put people off.
How could I get a frontend form to create a user without requiring a password? One thought it a hidden field and then programmatically changing the password to something random immediately after the save-user action, but I'm not sure how to do that.
Very open to other ideas too.


texts: Is it possible to validate whether all assets in an entry have been uploaded?

texts:
Is it possible that all assets are uploaded in a single entry and display success or fail in a friendly way?

Use case: Client uploads 2000 photos at a time in an entry and has to keep scrolling to the bottom of the asset popup box to see if all photos have actually "uploaded" or not.


texts: Is it possible to use images as variant selectors when choosing products?

texts:
I am fleshing out all the main parts of my commerce site and going through all the requirements needed.

I have installed the Craft Commerce plugin and set it up with required shipping, delivery, etc.

One thing I am trying to fathom and work out now is the ability to customise the variant selector. I want to use images from the fields in the product editor so you can select the variant colour/material/size as a different dropdown so we may have all three in one product.

When they are selected it would:

Change the image to the selected one
Also change price
Remember when added to cart that the selected items are the correct ones for the basket

Can this be done in Craft Commerce?


texts: When constructing an ECM, is it possible to compare two values?

texts:
My section has two numeric fields, lorem and ipsum. It's possible for users to enter any integer they want into these two fields.

I want to grab all results where lorem is greater than ipsum.

Here's my starting point...

{% set results = craft.entries.section('foo').limit(3) %}

How would I alter the above Element Criteria Model to only retrieve entries where the value of lorem is greater than the value of ipsum?


texts: Simple search using a single category in Craft CMS

texts:
I am relatively new to Craft and I am having a little trouble understanding how to build a simple search which will allow me to have dropdown of my categories which will return the selected category and return results on /products/results page.

I have a category called "Products" and have the following categories "Fruit", "Vegetables", "Dairy", "Herbs", "Eggs", and "Misc".  I would like to have these categories in a dropdown menu which would allow visitor to select the category they would like to view.  I also need it to show all product when they select "All Products", with "All Products" being the default value.

Thank you for your help.


texts:
I'm not a web developer but I seem to have taken over our business website.

It uses
apnexus
doubleclick and
google analytics

I need to make sure we are prepared for the GDPR and seek consent from any new visitor.

Can someone point me in the right direction?  Are these built into all Craft CMS sites?  Will they be updated to follow the new regulations?

thank you ...


texts: How can I fetch an entry's draft children?

texts:
When my users are previewing pages, we have a "child page list" component on the frontend that shows a list of the current entry's children. If any of these pages are draft, they don't show up using $entry->getChildren()->all().
I've tried swapping this to:
Entry::find()->status(['live', 'expired', 'pending'])->descendantOf($entry)->descendantDist(1)->site($this->locale)->all()

... but this still doesn't show the draft entries. Is this because a draft isn't considered an EntryModel, but an EntryDraftModel instead? If so, is there a way I can fetch all of the child entries regardless of their type and then output them?


texts: Register JS files at the end of the body tag in the Control Panel

texts:
I would like to add my own external JS sources at the very end of the body tag in the Craft control panel.

I've already tried using:

{% do view.registerJsFile("<CDN_URL>", {position:3}) %}

according to https://www.yiiframework.com/doc/api/2.0/yii-web-view#registerJsFile()-detail, but Craft is always adding its own JS sources after mine.

Any help would be appreciated!


texts: Load a specific file/CSS only in a certain page

texts:
I want to load a .css file only in a certain page.

What's the magic code I need?


texts:
Be warned this is sort of Docker related question too.

I try to build local development environment using Docker (nginx 1.16.1 + postgresql 12.1.0) running Craft 3.4.1.
I've came up to a point where I run the setup wizard over browser. During the steps (connection to database is skipped) I fill the required fields and proceed to final "Next" button where the installation step begins.

  Install failed  Please check your logs for more info.

PHPerrors log shows:

An Error occurred while handling another error:
PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation "queue" does not exist ...

Web log shows:

There is a lot of it but it's about info table and to summarise to one general sentence I've picked this line

ERROR:  relation "info" does not exist ...

What I'm able to:

I'm able to connect to database over docker CLI and PGadmin
I'm able to create database over docker CLI and PGadmin

What I'm not able to:

I'm not able to successfully run ./craft setup which reports back this failure SQLSTATE[08006] [7] could not translate host name "postgresql" to address: Name or service not known

Every image lives in it's own container and are connected over external network. If more info required I'd be happy to provide.

Is there anyone Who have experienced similar issue?


texts:
I need to batch process a set of data. To do this I am using the code below. I am trying to process 100 at a time, but the offset doesn't seem to work. It works the first time, but in the second iteration of the loop it doesn't set the offset properly.

  $criteria = craft()->elements->getCriteria(ElementType::Entry);
  $criteria->section = 'affiliates';
  $criteria->limit = null;
  $row_count = 6000;
  $batch_size = 100;
  $num_batches = ceil($row_count / $batch_size);
  $offset = 100;

  for ($j=0; $j <= $num_batches; $j++) {
      $query->setOffset($offset);
      $query->limit = $batch_size;
      $offset = $offset + $batch_size;
      $queryResults = $query->queryAll();
      $affiliates = EntryModel::populateModels($queryResults);

      foreach ($affiliates as $affiliate) {
        //process
      }
   }


texts: Entry validation not working when Publish live changes permission is not checked

texts:
when a user with no permission to publish is submitting a blank entry, the entry is saved anyway without any errors.

Here is the permissions set to the user group:

I have few required field as showed below:

And very sadly, the entry is saved as draft, entitled "New Entry":

This can't be a feature, is it?


texts: Trying to set an image URL using a global asset field

texts:
I've setup a global asset field so that a client can change a placeholder image that gets used throughout their website. I'm using the Imager plugin for my image transforms.

The following image code works fine when using a hard-coded image URL:

{% set image = 'http://placehold.it/450x225/eee/eee' %}
{% set transformedImage = craft.imager.transformImage(image, { width: 450, height: 225, }) %}

But when I replace the hard-coded image URL with the global asset field, it doesn't work:

{% set image = '{{ websitePreferences.placeholderImage.first.url }}' %}
{% set transformedImage = craft.imager.transformImage(image, { width: 450, height: 225, }) %}

I get this error message (Craft/Exception):

  Source folder “/Users/stephen/Repositories/repo-name-here/public_html./” does not exist

If I output the global asset field elsewhere in the template, I get this:

  http://my-locl-url.dev/uploads/images/Placeholders/placeholder-image.png

If I hard-code this URL into my image code, the image works fine. So does anyone have any idea why using a global for the placeholder image in this way isn't working? Thanks for any help.


texts: {% redirect "{{ entry.url }}" %} doesn't work

texts:
I've set up a structure channel that has entries at /services/slug however I want the /services template to redirect to the first entry in the services structure.

What I have now is:

{% for entry in craft.entries.section('services').limit(1) %}
  {% redirect '{{ entry.url }}' %}
{% endfor %}

However when visiting /services this redirects to a 404 page with url of /%7B%7B%20entry.url%20%7D%7D/

I also tried {% redirect "services/{{ entry.slug }}" %} but that didn't work either.

Is it possible to set up a redirect in the way that I am trying to do here?


texts: get post data after submitting User Profile Form for success message

texts:
After a logged-in user updates their profile on the front end, I'd like to redirect them to the same page but show a success message. I believe I can do this with craft.request.getPost() but it's not working for me.  Code below:

<input type="hidden" name="test" value="xyz">

and then

{% set success = craft.request.getPost('test') %}
{% if success %}
    Success message
{% endif %}

I can see "test" in my dev tools network tab but can't seem to access it.


texts: How to filter relational field types on their related content's status?

texts:
I have a Matrix field on Users. In that Matrix field is an Entries field. I need to pull all Entries from that field, regardless of the related Entries status.

The following code returns Users but the Users' anEntryField only shows the default 'live' entries.

{% set users = craft.users({
    with: [
        'myMatrixField:blockType.anEntryField'
    ]
}) %}

How do I pass status(null) to that field? Or, if it's actually getting all the Entries... how do I show them all?

I have tried:

{% if
    user.myMatrixField | length
    and
    user.myMatrixField.first().anEntryField.first() | length
%} ... {% endif %}

But nothing in that block is executed for users who's anEntryField contains an entry that is disabled or expired.


texts: How do you only show children of “active” parent using categories?

texts:
I'm currently using Categories to organize an inventory of products. The hierarchy is straightforward: category, subcategory, and single product entry. The url structure I'm are hoping to use reflects the hierarchy: homepage.com/products/category/subcategory/product

So far, I've been able to display the proper slug for the products section and output a simple nav menu. What I'd like to do now is refine the nav so that it only display the subcategories (children) of the category (parent) of product I'm on. I think I'm looking for something like this but for Categories + Channel section rather than a Structure section.

I have an idea of how to achieve this, but I'm having trouble getting it to work. I think what I'd like to do is pull the url segment, match it to a category, then display its children. I know I'm missing something basic or haven't fully grasped the syntax of Twig. Any help would be appreciated, thank you!

-- edit --

Marion's suggestion was right on:

{% set categories = craft.categories.group('products').level('1') %}

  {% for category in categories %}
    {% set activeCat = (category.slug == craft.request.segment(2)) %}

      {{ category.title }}
      {% if activeCat %}
        {% set subCategories = craft.categories.descendantOf(category) %}

          {% for subCat in subCategories %}

{{subCat.title}}

          {% endfor %}

       {% endif %}

  {% endfor %}


texts:
Looking for a way to show Channel entries directly on the sidebar for content editors. So if someone has access to:

DEFAULT STRUCTURE of Sidebar Menu

Entries ->

CHANNELS ->

News

News Item 1
News Item 2
News Item 3

PREFERRED STRUCTURE of Sidebar Menu

News

News Item 1
News Item 2

In other words, Content Editors don't need to see "Entries" and then "CHANNELS" to get to their section they update. When someone has permissions for a specific Section or Channel, it should be neatly accessible on the left side.

In Craft, what is the correct approach to make this happen?


texts: How to reference the current entry element in custom Control Panel templates?

texts:
This might provide it's own answer, but I thought I would ask to be sure. How do you reference the current entry in custom fieldType or CP templates? I have tried {{ entry.id }}, {{ element.id }} but neither work. Do you need to explicitly set these variables in your getInputHTML() function?

I see in the craft '_entry.html' template that {{ entry.id }} is used for a hidden field. Since that reference is not available, I assume that template variables are scoped to the template and not inherited by other templates on the same page?

Through trial and error I finally discovered the current entry can be referenced in PHP as $this->element;, and the id and section via $this->element->id, $this->element->section respectively. So, I could add entry as a template variable, but I just assumed it would already be there.

public function getInputHtml($name, $value)
{
    $entry = $this->element;
    return craft()->templates->render('myPlugin/fieldtypes/MyField/input', array(
        'name'          => $name,
        'value'         => $value,
        'entry'         => $entry
    );
}


texts: Is there a way to find out if images (assets) are landscape or portrait?

texts:
In a current project we will list entries in a masonry-style grid view where the entry’s respective cover image should be styled differently based on their image format. Landscape vs. portrait and -- of course -- square.

I haven’t found anything on here or in the docs pointing to a possible way of doing this.


texts: Links in e-mails are not properly formatted

texts:
I have a site where users can register and login. But in link 70% of the cases the accountVerification e-mail is not sent properly, resulting in users can't verify their account and thus can't login. They all get an Exception page when visiting the link. Below is the not properly formatted link (mark the “id” part):

/actions/users/setpassword/?code=5QJ_3LUkVKkUpX2OVJITkFScUzYFxjnC&id;=49d83ace-1b12-45fa-a24a-9882c0027321

The error in the logs is like this one:

[exception.Craft\HttpException.400] exception 'Craft\HttpException' with message 'Parameter "id" bestaat niet.' in /home/xxxxxx/craft/app/services/HttpRequestService.php:586

I can’t seem to find a solution for this and actually expect I can’t be the only one with this problem. In the e-mail I'm already giving the users two links to verify their account, one normal {{ link }} tag and an {{ link | escape }} tag. But it still doesn’t work. Maybe anyone of you can help me? Would be great, thanks!


texts:
Is there a way to search for entries which do not have content in an entry field property on the CP?
I've tried -field:* which doesn't return anything, but if I remove this there are entries which have an empty field.
Is there something special to add to get empty entry fields?


texts: How to do smart upselling and cross-selling in Craft Commerce

texts:
I want to have the following features on my Craft Commerce site:

Often bought together: Bundling
You may also like: Upselling/cross-selling/personal recommendations
Accessories

I realize that it's easy to define custom fields that let me associate products with each other - but I am not looking for a manual method.

I did a search on "ai powered cross selling ecommerce" and found a few stand alone solutions and some specifically tailored to e-commerce solutions like Magento.

But what would you do? Have any of you experiences with this kind of machine learning/ai algorithm for cross-selling/product recommendations/personalization?


texts:
I am setting attributes on my record using a models' attributes (that has validated successfully). I cannot figure out why the values aren't assigned. I can manually assign each one but that's redundant.

// Set attributes
// Massive assignment will only be made for fields which have passed some explicit validation rule.
if ($model->validate())
{
    $purchaseRecord->setAttributes($model->getAttributes());
    var_dump($model->snipInvoiceNumber); // works
    var_dump($purchaseRecord->snipInvoiceNumber); // null value
    $purchaseRecord->snipInvoiceNumber = $model->snipInvoiceNumber; // works
}

UPDATE:
Per comments on this thread I looped through and set the attributes individually. Anyone have insight on why setAttributes didn't work?
Save contact form data to database

This is what I used instead of setAttributes (plural).

foreach ($model->getAttributes() as $key => $value ) {
    $purchaseRecord->setAttribute($key, $value);
}


texts: Sprout Import: No Changes When Updating Entry

texts:
I'm trying to update existing entries with Sprout Import but when I run the import even though there are no errors the entry's data is not updated. I simplified the JSON script as much as I could and it's still not working:

[
    {
    "@model": "barrelstrength\\sproutbase\\app\\import\\importers\\elements\\Entry",
    "related": {
      "relatedResources": {
          "@model": "barrelstrength\\sproutbase\\app\\import\\importers\\elements\\Entry",
          "params": {
              "slug": "test-import-child",
              "sectionId": 2
            }
        }
    },
    "settings": {
      "updateElement": {
        "params": {
          "slug": "test-import-parent",
          "sectionId": 2
        }
      }
    }
  }
]

I also tried doing it with just a plain text field instead of a relationship field and still didn't get any change.

[
  {
    "@model": "barrelstrength\\sproutbase\\app\\import\\importers\\elements\\Entry",
    "content": {
        "body": "Lorem ipsum dolor sit amet."
    },
    "settings": {
      "updateElement": {
        "params": {
          "slug": "test-import-parent",
          "sectionId": 2
        }
      }
    }
  }
]


texts:
From within a plugin, I’m trying to filter users by a custom field.

An external post request will supply a variable which I want to match the custom field to. I then want to respond to that request with other user custom fields as JSON.

For example the incoming post contains customHandle1=A, I then find all the users where customHandle1=A and return customHandle2 and customHandle3 data.

How would I do that?


texts: How to query for multiple relations with SuperTable

texts:
The relevant sections for this question are:

Event: One relevant field. guestAllocation (SuperTable). Guest allocation is a table which selects a Partner (Entries) and how many people that partner is allowed to invite to an event
GuestList - Two fields. relatedEvent (Entries) and guestNames (table)

Each Partner creates an Entry in the guestList channel. When they want to update the names of who they're inviting, they edit their post instead of creating a new one.

I'm trying to write a conditional which will let me check if there's already an entry in the guestList channel which is both related to that partner AND the event we're currently looking at. I need to check this as I have to update that Entry instead of creating a new one if it exists. The form is displayed on the Event page, so the entry variable is the current event we're dealing with.

I can't get my head round the relations documentation. How do I write this? The following is returning no results:

{% set partnerGuestList = craft.entries.section('guestList').relatedTo(
    { sourceElement: entry }, {# this event #}
    { targetElement: currentUser.partner.first() } {# current partner #}
) %}


texts: How do I return ALL entries that are singles

texts:
I'm trying to generate a sitemap and wish to output all the entries that have a section type of 'single' but can't get the the correct syntax.

All of the entries need to return 'single' for {entry.section.type}.

{# This query doesn't work but hopefully helps demo the above question #}

{% for entry in craft.entries.section({'type':'single'}).order('id asc') %}
    <url>
        <loc>{{ entry.url }}</loc>
        <lastmod>{{ entry.dateUpdated.atom }}</lastmod>
        <changefreq>weekly</changefreq>
        {% if entry.section.isHomepage() %}
            <priority>1</priority>
        {% else %}
            <priority>0.8</priority>
        {% endif %}
    </url>
{% endfor %}

Edit:

This query does work but it's a slow bad way of doing it as it gets EVERY entry and filters after the fact:

{% for entry in craft.entries.order('id asc') if entry.section.type == "single" %}
    <url>
        <loc>{{ entry.url }}</loc>
        <changefreq>weekly</changefreq>
        {% if entry.section.isHomepage() %}
            <priority>1</priority>
        {% else %}
            <priority>0.8</priority>
        {% endif %}
    </url>
{% endfor %}


texts:
On Craft 3 I am iterating over matrix elements and I need to check if a certain property "videoPoster" exists. It's an asset field, so I actually want to check its length, but I'am already failing to check if it's available...

"ce" is one block of my matrix, this is what I'm doing:

{{ ce.videoPoster is defined ? 'yes' : 'no' }}

Works, gives me a nice "Yes"

Anything else does not work:

{{ ce.videoPoster is defined and ce.videoPoster ? 'yes' : 'no' }}
{{ ce.videoPoster is defined and ce.videoPoster is not null ? 'yes' : 'no' }}
{{ ce.videoPoster is defined and ce.videoPoster | length ? 'yes' : 'no' }}

Exception: Calling unknown method: craft\elements\MatrixBlock::videoPoster()

What is the correct check? I just want to know if I can call ce.videoPost.one()


texts: How can I use the password confirmation modal on other forms?

texts:
While logged into the Control Panel, you can edit your account information. When you try to change your email address or password, Craft asks you to enter your current password (for security reasons).

Is it possible to borrow this password confirmation security feature?

I've built a form which is very powerful and contains sensitive data. I want the user to be triple-sure that they want to submit the form... Forcing users to re-enter their password seems like a good way to minimize accidents.


texts: Asset routing issue in combination with slug and date

texts:
Normally I add images to a post through a field for it, but now I thought I'd just use the uploader in the text/newspost field. However, this gives me the following problem.

When on index.htm for the blog channel the image is shown.

http://inquisimunda.evinwijninga.com/uploads/Facebook-Banner.gif

When I go to the the posts page itself however, the post isn't shown as it can't be found. It also isn't shown in the text editor when I edit the post. (Broken image link).

http://inquisimunda.evinwijninga.com/article/2015/uploads/Facebook-Banner.gif

I have never tried to fix routing issues before as I had never had any issues like this before.

Is there a quick fix for this?


texts:
ENVIRONMENT: Craft 2, Sprout SEO 3.4.2, Bob Olde Hampsink's "Tag Manager" plugin.

The site has a bunch of articles organized by category and tags, and I've got a template for showing articles by tag (ex: https://www.therapyinphiladelphia.com/tips/tag/employment/).

In Sprout SEO I've "Enabled Meta Details fields" and attached them to Craft's TAGS using the Tag Manager plugin. This allows me to insert custom metadata for each TAG just like I would on a normal Craft entry.

So in theory the {% sproutseo 'optimize' %} template tag on my "articles by tag" template should pick up the custom values entered into the Sprout SEO meta details fields for the tag... just like it would for a normal entry.

However it's not picking up anything, it just reverts to the Globals set under Sprout SEO's settings.

To debug I've done a couple of things:

Under Sprout SEO > Settings > Advanced > Enabled custom metadata variable (giving it the name metadata), and
turned on Craft's dev mode and echoed {{ dump(metadata) }} into the template.

The output of {{ dump(metadata) }} shows the Globals set under Sprout SEO's settings and not the custom metadata entered into the Tag Manager for the selected tag.

I've also tried using the {% do craft.sproutSeo.meta() %} function to manually override the automatic output of the {% sproutseo 'optimize' %} template tag.

{#
 # ARTICLES BY TAG TEMPLATE
 #}

{% sproutseo 'optimize' %}

    {% do craft.sproutSeo.meta({
      section: 'Self Help Tips',
      title: tag.title,
      description: metadata.metaDescription|striptags|slice(0, 150),
      canonical: craft.request.url,
      ogTitle: tag.title,
      ogType: 'article',
      ogUrl: craft.request.url,
      ogImage: metaImage.url(),
      ogImageWidth: metaImage.width,
      ogImageHeight: metaImage.height,
      ogImageType: metaImage.mimeType,
      ogSiteName: siteName,
      ogDescription: metadata.description,
      twitterCard: 'summary',
      twitterSite: '@twitteruser',
      twitterCreator: '@twitteruser',
      twitterTitle: tag.title,
      twitterDescription: meta.search.description,
      twitterUrl: craft.request.url,
      twitterImage: metaImage.url()
    }) %}

This works if I enter hardcoded strings in, but the metadata variable in the template doesn't pick up the custom metadata entered for the tag.

Is this a bug? Is the Sprout SEO plugin only set up to work with ENTRIES, and not TAGS?


texts: getNextSibling for next product in product type

texts:
I’m setting up a Craft Commerce website, and at the end of the product pages, I’d like to add a link to the next product in the same product type as the current product.

For regular entries, I used {{ entry.getNextSibling().url }} to get the next entry in the current section, but I can’t figure out how to get the same result for the products.

Thanks!


texts:
I have been stuck on trying to make an ajax call to a custom plugin controller in Craft 2 for a few days after trying everything from following the documentation for Craft 2 as well as looking up other posts that basically reiterate what the documentation says, but nothing seems to work. According to the documentation for Craft 2, I should be able to use:

[PluginHandle]/[ControllerName]/[ActionName]

in a hidden field. I've even tried using the full method name, actionGetLocations, just to rule that out. Here is what I have:

<input type="hidden" name="action" value="/actions/googleMap/getLocations">
<input type="hidden" name="redirect" value="{{ siteUrl }}map-test">

Here is my controller:

<?php

namespace Craft;

class GoogleMap_MapController extends BaseController
{
    public function actionGetLocations()
    {
        $this->requireAjaxRequest();

        return $this->returnJson([
            'success' => [
                'state' => "This would be states",
                'locations' => "This would be locations"
            ]
        ]);
    }
}

My controller file is named GoogleMap_MapController.php to follow the naming scheme. I also have my ajax request, which needs to be written in vanilla javascript for this site:

var xhr = new XMLHttpRequest();
            xhr.open('POST', '/actions/googleMap/getLocations');

            xhr.onreadystatechange = function() {
                if(xhr.status === 200) {
                    console.log(xhr);
                }
                else {
                    console.log("The request failed, returned status of " + xhr.status);
                    console.log(xhr);
                }
            };

            xhr.send(data);

I get a 404 error for page not found, which makes sense since it's not really a page, but the documentation says that it will attempt to determine if the request URL is an action first. I tried changing the ajax call to post to '/' instead, but that returns the HTML from the page '/' successfully, which is not what I'm trying to get at all. I've tried sticking my hidden input tags in a form tag, however the submit causes the page to redirect to this non-existent route. I added in onsubmit="event.preventDefault();" to my form tag, and while it doesn't redirect, I still get a 404 error response. I'm completely at a loss at this point any help is greatly appreciated.


texts: Craft 3 Element Api when system status is disabled

texts:
Using Craft 3 RC14
System status is set to off

Wondering if anyone has approached the same problem as I did. If there is a way to use element api while the system status is disabled?

I have tried to check the app's status within the element api using \Craft::$app->isSystemOn and it does display true when the status is enabled, on the other hand it doesn't even go to the element.api and returns 503.

I have to keep the status disabled as during the development I don't want any search engine to crawl the content of the website before the actual launch date.

Is there way to set the status on the api end or any other solution that would make my api active while the website is disabled?


texts: Uploading local asset hangs and produces jQuery console error

texts:
So I have created an Assets field and am using it in one of my Entries. However, when I try to upload an image, it just keeps loading. I am getting the following console error:

Any ideas why? Thanks!


texts: Is it possible to add an entry value to the entry URL Format?

texts:
I try to compose an entry URL for artists pages with first name and last name.

Now:

artists/{slug} = artists/{{ entry.title }}
{slug} = {{ entry.title }} = Artist Last Name

What I want to add at the end of the URL (Plain Text field):

{{ entry.artistFirstName }} = Artist First Name

What I try to get, but which is not working:

artists/{slug}-{{ entry.artistFirstName }}

Is it possible? how? And how can I add a conditional to check if entry.artistFirstName is defined?

Thanks!


texts: Renaming files on Amazon S3 through Craft backend

texts:
I've read somewhere you can't rename files on Amazon S3, which might explain my not being able to rename assets hosted on S3? Or, have P&T found a way around this and I've just not set the right user permissions?

My current permissions for this user are:

        "Action": [
            "s3:ListAllMyBuckets",
            "s3:PutObject",
            "s3:PutObjectAcl",
            "s3:DeleteObject"
        ],

Thanks,
Clive


texts: How do I get different URL Format with parent/child structures & how do I display different templates?

texts:
I need to create a features structure section for a website that will have parent features and child features.

Q1: How do I get different URL Format for parent & child pages?

I need the parent features here: website.com/features/parent-feature
And the Child features here website.com/parent-feature/child-feature

Q2: How do I display the Parent & Child in different templates? I want the parent features to look more dominant than the child features.


texts:
How to use select dropdown with entries/saveEntry for an entry field?

I have an entry with a field that is another entry, which I want to update with a form:

<form method="post" accept-charset="UTF-8">
  {{ getCsrfInput() }}
  <input type="hidden" name="action" value="entries/saveEntry">
  <input type="hidden" name="entryId" value="{{ entry.id }}">
  <label>Vendor
    <select name="fields[vendor][]">
      <option>---</option>
      {% for v in craft.entries.section('vendors') %}
        <option value="{{v.id}}">{{v.title}}</option>
      {% endfor %}
    </select>
  </label>
  <input type="submit" value="Submit"/>
</form>

This works fine, except if nothing is selected in the dropdown (<option>---</option>). In that case, the POST value for fields[vendor][] is ---, and I get a SQL foreign key constraint error.

I have also tried <option value="">---</option> and <option value="NULL">---</option> with no better outcome.


texts:
I'm running Craft CMS on OS X Yosemite (Server.app) and cannot upload PNG images. JPG uploads are working as expected. I get a log message like the following:

2015/01/15 08:39:08 [error] [exception.Imagine\Exception\RuntimeException] exception 'Imagine\Exception\RuntimeException' with message 'Unable to open image .../craft/storage/runtime/temp/assets54b77cabe51c25.46473389.png' in .../craft/app/vendor/imagine/imagine/lib/Imagine/Gd/Imagine.php:96
Stack trace:
#0 /*/craft/app/etc/io/Image.php(136): Imagine\Gd\Imagine->open('...')
#1 /*/craft/app/services/ImagesService.php(84): Craft\Image->loadImage('...')
#2 /*/craft/app/services/ImagesService.php(153): Craft\ImagesService->loadImage('...')
#3 /*/craft/app/assetsourcetypes/BaseAssetSourceType.php(183): Craft\ImagesService->cleanImage('...')
#4 /*/craft/app/assetsourcetypes/BaseAssetSourceType.php(145): Craft\BaseAssetSourceType->insertFileByPath('...', Object(Craft\AssetFolderModel), 'HSS_Highlife_20...')
#5 /*/craft/app/services/AssetsService.php(673): Craft\BaseAssetSourceType->uploadFile(Object(Craft\AssetFolderModel))
#6 /*/craft/app/controllers/AssetsController.php(71): Craft\AssetsService->uploadFile('1', NULL, 0, NULL)
#7 /*/craft/app/framework/web/actions/CInlineAction.php(49): Craft\AssetsController->actionUploadFile()
#8 /*/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#9 /*/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#10 /*/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#11 /*/craft/app/framework/web/CWebApplication.php(282): CController->run('uploadFile')
#12 /*/craft/app/etc/web/WebApp.php(754): CWebApplication->runController('assets/uploadFi...')
#13 /*/craft/app/etc/web/WebApp.php(261): Craft\WebApp->_processActionRequest()
#14 /*/craft/app/framework/base/CApplication.php(180): Craft\WebApp->processRequest()
#15 /*/craft/app/index.php(62): CApplication->run()
#16 /*/public/index.php(14): require_once('...')
#17 {main}
REQUEST_URI=/index.php?p=admin/actions/assets/uploadFile
HTTP_REFERER=http://*/index.php?p=admin/entries/banners/5-highlife-vanguard
---
2015/01/15 08:39:08 [error] [application] Unable to open image craft/storage/runtime/temp/assets54b77cabe51c25.46473389.png

It looks like a problem with the Imagine library not being able to open the uploaded PNGs?


texts: How to display number of entries for a tag and not display if no entries?

texts:
I want to be able to display the number of entries that have a tag. Like:

Fruit (9)
Vegetables (4)

I also want to avoid displaying any tags without any related entries.

My code right now looks like this:

{% extends "_layout" %}
{% set title = "Tags" %}
{% block content %}
{% for tag in craft.tags.order('title') %}

}{{ tag.title }}

{% endfor %}
{% endblock %}


texts: Template logic to address a third URL segment

texts:
I'm using Craft 3, and I'm struggling to make sense of how to address the following. (I've not had need to venture into a third URL segment before.)

I have a url of the form:

stories/{slug}

served by a template:

stories/_entry

I'm aware that the 'entry' variable gets set automatically. So far so basic.

But I also want to address urls of the form:

stories/{slug}/{variable}

…where variable is used to fetch content from a specific Matrix row in the entry that matches slug.

It is important that variable forms a third segment addressable as its own page, and not just a URL query parameter.

I have tried 2 approaches:

Getting segment 3 and then using it in a conditional inside of stories/_entry:

{% set seg3 = craft.app.request.getSegment(3) %}
{% if seg3|length %}
    {% include 'partials/extract' %}
{% else %}
    {% include 'partials/story' %}
{% endif %}

…but when seg3 is not empty Craft says:

  Template not found

Setting a route to a different template:

stories/{slug}/{*}

…is processed by:

stories/_extract

…in which, as a basic test I have:

{% block meta %}
    <title>{{ entry.title }}</title>
{% endblock %}

…but Craft then reports a Twig runtime error, saying:

  Variable "entry" does not exist

So I tried using:

{% set seg2 = craft.app.request.getSegment(2) %}
{% for entry in craft.entries.section('stories').slug(seg2).all() %}
    {% block meta %}
        <title>{{ entry.title }}</title>
    {% endblock %}
{% endfor %}

…but that makes no difference.

Is my approach 2 definition of entry wrong?

Why does a non-empty value in segment 3 cause approach 1 to fail?

I'm obviously missing something fundamental here. Any pointers much appreciated.


texts: Migrating entries to custom element and UID

texts:
I want to migrate some entries and its content to a new table in our plugin. Below is a simplified SQL that seems to do the trick.

insert into craft_myplugintable(id, field1, field2, field3, dateCreated, dateUpdated, uid)
select entries.id, content.field_field1, content.field_field2, content.field_field3, entries.dateCreated, entries.dateUpdated, entries.uid
from craft_elements elements
  join craft_entries entries on elements.id = entries.id
  join craft_entrytypes types on entries.typeId = types.id
  join craft_content content on entries.id = content.elementId
where types.handle = 'mySection';

update craft_elements elements
  join craft_myplugintable myplugin on elements.id = myplugin.id
set type = 'Plugin_ElementType';

Is this method safe? Should i use a migration file and let craft set the UID? I'm not sure what the UID field is for. Keep in mind that we no longer need the entries, so they can be deleted if this is wrong.


texts: Method (plugin free?) to combine search results across multiple searches (and element types)

texts:
So I have created a combined search for products and entries using the new Craft 2.5 search score.  It's working well, but...I was hoping to be able to do this without a plugin if possible ... but it doesn't seem immediately possible to do unless I am missing something.

If anyone knows a way, it would be much appreciated.  In the meantime I'll post the solution I have come up with as an answer below.


texts: Just starting to evaluate - some basic questions

texts:
We are just in the CMS evaluation stage, so, I have some early questions:

We don't want to create another layer of user logins, can Craft authenticate users using oauth or active directory?
As Craft users -> Why is Craft better than Drupal, Wordpress, Joomla?


texts: How can I output ALL strings from a lang file?

texts:
I need to output a JSON object containing all of the key/value pairs in either /translations/{myLocale}.php or /craft/plugins/myplugin/translations/{myLocale}.php.

I can't see any way of doing that?

I can see that I can call craft()->getComponent('messages') but that will retrieve all of Craft's internal translations - I only want the messages I have defined in one of the files above.


texts: What media type are SVGs treated as in assets?

texts: When SVGs are uploaded to assets what media type does CraftCMS associate them with? Image, Document, HTML or XML?


texts: Use loop index number in a Twig variable

texts:
Let's say I have 5 Craft fields named "item1" thru "item5."

Instead of writing out each variable...

{{ entry.item1 }}
{{ entry.item2 }}
{{ entry.item3 }}
{{ entry.item4 }}
{{ entry.item5 }}

How can I create a loop to do this for me?

I've tried this...

{% for i is 1..5 %}

    {{ entry.item ~ loop.index }}

{% endfor %}

But it returns the error:

  Craft\EntryModel and its behaviors do not have a method or closure named "item".


texts: Get dropdown / checkbox / multiselect field values on frontend submit

texts: I would like to allow registered users to submit entries to sections. The documentation didn't mention how to get the values and labels of dropdown / checkbox / multiselect fields to show them as options on the submitting page. I can't use the entry variable because the entry is not saved yet.


texts:
I am trying to accomplish targeting but wondering if there is a way to combine these two? I took a look around and in the Craft 3 docs but I am a bit turned around on this, really would appreciate some help with it.

{% set parts = craft.categories.group('part').slug( urlSlug2 ) %}
{% set models = craft.categories.group('model').slug( urlSlug3 ) %}

{% set entries1 = craft.entries.section('flightcompany').relatedTo({
    targetElement: parts,
    field: 'partsModels.part'
}).limit(5).all() %}

{% set entries2 = craft.entries.section('flightcompany').relatedTo({
    targetElement: models,
    field: 'partsModels.model'
}).limit(5).all() %}


texts: How do I test if Craft CSRF Protection is properly enabled?

texts:
Craft supports enabling CSRF protection on our front-end forms.  They even have a nice, easy-to-follow, help page called "How do I enable CSRF protection?"

Let's say we pull that all off without a hitch. Our forms output the csrfTokenName and csrfToken and the browser cookie is generated just as expected.

Now, how do we test if it is actually working?  Are there any steps an average, not-very-technical developer can take to see if CSRF protection is behaving as expected?


texts: How can I restore Matrix content after accidentally changing its field type?

texts:
We accidentally deleted all our body text on all our pages, how do I redo my website to a older version. (24 hours ago)
We changed matrix to assets and after that every body text disappeared.


texts: How to Access the Twig Attribute Name from the Fieldtype Class

texts:
I want to be able to output different values for my fieldtype depending on the twig attribute. So {{ entry.myField }} would output AK by default, but {{ entry.myField.label }} would output Alaska. Currently I'm using the normalizeValue() method to handle all this, but I need to know which attribute (if any) is being called by the twig template. How do I get that information?

A very basic example of what I'm thinking of would be:

public function normalizeValue($value, ElementInterface $element = null)
{
    $states = array(
        'AK' => 'Alaska',
        'AL' => 'Alabama'
    );

    if( twig.attribute == 'label' )
    {
        return $states[$value];
    }
    else
    {
        return $value;
    }
}


texts:
My usual development process is to build the site locally, then upload on a staging subdomain for client reviews, going back and fourth between the two environments for updates, before deploying it on its live environment.

From what I understand you can use the one licence key on multiple environments but you can only then login to the Admin area from one of them? Which would cause me issue when I have the staging site up but I'm working between that and the dev version?

Alternatively I can use Craft for 'Free' using a appropriate .dev or staging URL (eg. http://staging-subdomain.mysite.com) and then make sure the paid for license is in place on the live version. Is that correct?


texts:
I'm creating a FieldType plugin, but I need the entry's ID in the front-end, I suppose I can get it within the controller, something like

craft()->entryId

$entryId = IN HERE;

$options = array(
    'coreUrl' => getenv('ENV_CORE_HOST'),
    'newEntry' => false,
    'entryId' => $entryId
);

craft()->templates->includeJs("$('#{$namespacedId}-field').whatever('" . json_encode($options) . "');");

I can get the ID in the URL with Regex and stuff, but I wouldn't like to rely on that.

And suggestion?


texts: Craft Commerce - Purchasables and multiple gateway accounts

texts:
Time for my first question. "we have a client..." :)

I'd like to achieve something like:

A visitor (User A) is able to register and create a 'Team' Entry.
They then invite new users (Users B, C, D, E etc) to register by adding them to their 'Team' Entry(s)
User A then pays for the Teams they have created - I am planning on constructing a Craft Commerce 'purchasable' item for each Team Entry and passing all of the Teams to the Cart for the usual Checkout process...

Challenge 1: The client would like payments for a given city to be directed to a specific Payment Gateway i.e. Payments for the Paris Team Entries, should go to a Stripe account which the Paris office has access to and can administrate.

In a similar way, payments for London team entries, need to go via a different Stripe account which only the London office has access to.

(there will be over 13 different cities in various countries by 2017 with more added thereafter)

Q: How could I extend or override the default Stripe Account in Craft Commerce settings, based on the location of the Event which a Team is registered for? e.g. I could use Stripe API custom fields in the City Entry.

Challenge 2: Allowing a user to pay for creating Team entries - I spotted this solution by Mr Kelly from earlier this year: Using Commerce to pay for posting entry

I'd appreciate any solutions or ideas you might have - thanks in advance!

Matt


texts: How do I get the number of days in the previous month?

texts:
I am working on a calendar, and so far I know how to get the number of days in the current month.
{% set daysInMonth = time|date('t') %}

But how can I get the number of days in the previous month?

Thanks in advance.


texts:
We're just looking at potentially using Craft as a CMS to serve up content to a mobile apple/android app. Ideally content would be delivered as JSON and there be some sort of authentication from the app side (like an api key) as some of the content isn't intended to be publicly accessible. Can craft do this?

Many thanks!


texts: How to automatically remove entries after a certain time?

texts:
I haven't found anything similar to this. But I was wondering if it's possible to delete certain entries after a certain time?
For example: User fills in form and adds contact entry - after 2 weeks this entry gets removed automatically. This way the database won't fill up, and the overview will stay clean.
I was thinking a cronjob every 24h that checks the postdate and when the postdate is over 2 weeks it gets removed. However I'm not sure if this is possible with craft cms?


texts: Can entries be returned based on checkbox selection?

texts:
I have a section with entries which I wish to push to specific parts of the website.
I know I could filter them with a Category but the section already has a category so I would like to use checkboxes.

The checkbox only has 3 options so I could like to return those that are checked for a specific section.
Is this possible with checkboxes?
Been trying this but not getting anything returned:

  {% set entries = craft.entries.section('newsMedia').order('postDate desc').limit(7).search('zone:pupil')%}


texts:
I have a User entries field called 'company'.
I'm writing a bespoke plugin to manage users in the front-end and was wondering how I can access the content of this field in my plugin via the user model?

Any thoughts as struggling a wee bit here!


texts: How to handle soft delete behavior for a custom Element with custom content tables

texts:
I have a custom Element (a Form Element) that adds a custom content table for each Element that gets created (similar to how the Matrix Field creates a custom content table for each field). Users can submit data to another custom Element (Form Entry Element) that stores data in that content table.

In my case, when a Form Element is soft-deleted it would need to preserve the custom field layout, tabs, fields, and related content table for the Form Element, along with all the related Form Entry Elements that get added to the content table.  And then, if the item was not restored, when Craft purges old Elements from the Trash, all of those items would also need to be deleted.

What are the general considerations I need to know about to handle soft deletes correctly? Are there any specific files or methods in the Craft codebase I can take a closer look at to better understand how this behavior works at the point of the initial soft delete and during the cleanup when things get hard deleted?


texts: Charge 2 - Stripe form fields not showing

texts:
I just had a fresh install of Charge 2 and my Craft version is Craft CMS 2.6.2989. However as long as I have {{craft.charge.setPaymentOptions()}} in my template, all my form fields disappear and show up again after I remove this line.

{% extends "_layout" %}
{% set title = "Bookings" | t %}

{% set entry = craft.entries.section('bookings').first %}

{% block content %}

            {% if entry.heading | length %}

{{ entry.heading }}

            {% endif %}

            {% if entry.featureImage | length %}

            {% endif %}

            {% if entry.introText | length %}

{{ entry.introText }}

            {% endif %}

            {% if entry.body | length %}
                {% include '_partials/_body' %}
            {% endif %}

{{ "Make a Payment" | t }}

                <form id="charge-form" method="post" data-publicKey="{{ craft.charge.publicKey }}">
                    {% set chargeOptions = {'planAmount' : 99} %}
                    {{craft.charge.setPaymentOptions(chargeOptions)}}
                    <input type="hidden" name="action" value="charge/charge"/>

                    Receipt Email
                    <input type="text" name="customerEmail" value="{{ currentUser ? currentUser.email }}" id="customerEmail"/>

                    Card Number
                    <input type="text" data-stripe="number" placeholder="•••• •••• •••• ••••" id="cardNumber"/>

                    Card Expiry
                    <input type="text" data-stripe="exp" placeholder="mm / yy" id="cardExpiry"/>

                    Card CVC
                    <input type="text" data-stripe="cvc" placeholder="123" id="cardCvc"/>
                </form>

    {% includeJsResource('charge/js/jquery.charge.js') %}
    {% includeJsResource('charge/js/stripe_v2.min.js') %}
    {% includejs %}
        $(this).charge();
    {% endincludejs %}
{% endblock %}

I can't see what's wrong with my setup...


texts: Is there a way to purge old data in a table?

texts:
I have some tables in a matrix field and when I created the columns, originally I named them Col 1, Col 2, etc. That made sense to me but later I decided that since the client will be entering data, it'd make more sense to name them Column 1, Column 2, etc.

I renamed them but that was after I'd entered a bunch of content. So now in the Craft admin, I only see the new names, but when I loop through the entries in the table rows, all of the old entries are there as well.

Is there a way to purge that old data? I want to give the client to enter in the number of a column so you can add a highlight class to it. Right now, as I loop through the entries in those rows, it hits both old and new content and you can't get a dependable count.


texts: Any good tutorial for plugin developement? I am entirely lost

texts:
I understand Craft Templating pretty well, but when it comes to programmation I am entirely lost, I don't get how it works. I used to use CodeIgniter a lot, which is a MVC as you guys may know. In CodeIgniter, everything goes through the controller, then in the controller, I call models. In models, I interact with database and then return the data to the controller and then display a view. In Craft, it doesn't seems to work like this. Is there any good tutorials for "programming" in Craft or develop a plugin? Like how controllers, models, services and events works? Or is there any good people willing to help me?

I want to use Craft so much, I just need to understand it before I use it at large for my client's projects.

I appreciate your help.


texts: Why am I getting error: Object of class Craft\ElementCriteriaModel could not be converted to int

texts:
We just created an entry and hit save.  When we go to the front end of site we get a popup error that reads:

  Object of class Craft\ElementCriteriaModel could not be converted to
  int

What does this mean and how do I troubleshoot it


texts: Image transform in a multi language site gives wrong getUrl()

texts:
I have a multi language site with /nl and /en in my url.

mysite.dev/nl
mysite.dev/en

This is my configuration on general.php

'mysite.dev' => array(
    'devMode' => true,
    'translationDebugOutput' => false,
    'siteUrl' => array(
        'nl' => '//mysite.dev/nl/',
        'en' => '//mysite.dev/en/',
    ),
    'environmentVariables' => array(
        'siteUrl'        => 'http://mysite.dev/',
        'basePath' => '/Users/lisavandaele/documents/mysite/public/',
        'baseUrl'    => 'http://mysite.dev/'),

),

In my asset transform settings I made: thumb (width 120, height 90, crop)

In my twig I use:

{% set asset = entry.afbeelding.first() %}
            {% if asset %}

             {% endif %}

The url he uses is: //mysite.dev/nl/cpresources/transforms/1?x=UeS4gtVAw

if I go to the url without the /nl, I can view the image and I see he is rendered in my assets. ==> //mysite.dev/cpresources/transforms/1?x=UeS4gtVAw

But how can I use the correct url without the language parameter (/nl or /en) so my image transforms and can be viewed on my site.

I tried lots of configs, what am I overlooking?
I also cleared my cache and images evertime I changed my configuration but nothing worked...


texts: Updating all entries URIs after changing entry URL format

texts:
After publishing some entries, I've changed the section setting "Entry URL Format" from news/{slug} to news/{id} but I had to re-save every entry to reflect the change.
Is there a better and fast way to update all entries URIs after changing the entry URL format?


texts: Conditional check if Matrix block field is empty (no content)

texts:
I'm having a difficult time with what seems like a fairly straightforward problem:

I'm listing businesses and their related hours of operation (days/times). I'd like to set up a conditional statement that checks if a Matrix field has content—if so, display hours. If not, display message. My code is as follows:

{% if entry.hours.block('days')|length %}

      {% for block in entry.hours %}

        {{ block.days }}
        {{ block.times }}

      {% endfor %}

{% else %}

We're still trying to track down hours.

{% endif %}

I've also attached a screenshot of my Matrix setup. Thanks so much in advance]1


texts: File Upload Validation in a Front End form

texts:
Good Evening.
I have a front end form that allows users to upload up to 4 images to an asset field, however the file chooser allows for more than 4.  This causing an issue with any further updates at the front end due to an error occuring in the back end due to the excess files.  Is there an easy way to add some validation to this field to check before it allows the submission?


texts: How do I enforce stronger password requirements on my Craft site?

texts:
Craft’s only password requirements are that it is between 6 and 160 characters long. I want to require my users to enter passwords that are at least 7 characters long, with at least one number and one capital letter.

Is it possible to enforce these stricter requirements, or do we have to wait for this feature request to be accepted?


texts:
On certain pages of my site, I download and display resized (using the Imager plugin) images from remote site.

Now, sometimes that remote site returns error and in such case Imager is throwing exceptions, blocking the whole page from being viewed.

Now, is there a way to suppress server errors when possible, e.g. write them to log file and don't stop page processing?

devMode is set to false.


texts: How to create different template for specific page?

texts:
I have added a "newsletter" page under Admin > Entries > Page [New Entry]
And the page is opening fine on the url xyz.com/newsletter
But I want to assign a different template to this url, how can I do that?
I tried creating a folder at /templates/newsletter/index.twig but that is not working at all.


texts:
I am a Joomla developer who has been asked to start developing Craft plugins and I'm afraid my brain is so moulded to the joomla way of doing things that I cannot even see how the template links to the plugin and fires events

I'm especially interested in form processing (being the cornerstone of application functionality) and I've been taking a look at the contact form plugin. In the contact.html template I can see {{ getCsrfInput() }} which is twig syntax for calling a method- but there is no method called getCsrfInput() anywhere in the plugin. However it works, hidden fields are returned with an 'action' pointing to contactForm/sendMessage which (I'm assuming the Craft app decides, because there is no form tag action) fires the actionSendMessage event in the contact form plugin.

I just don't see the sequence! I can program PHP fine, but (perhaps due to ONLY doing things the Joomla way) don't see how plugins are called/included in a page.

It's a silly example, but could someone explain to me how I could get a function to just echo Hello World on a page:

function printHello()
{
echo 'Hello world!'
}

Would this go in the plugin root class? If so, what do I put in the example.html template to call this plugin function?

If I can do that then I can (presumably) use it to do everything else. Just 'including' a PHP function on a page doesn't seem like the Craft way of doing thing- I've read about hooks and events, and they don't make sense to me. Hooks seem to link a plugin to a URI, and it seems to suggest that you don't need to put anything into the template html calling the plugin. The Other, 'Events', is all PHP, so I'm assuming isn't intended to be put into the template files (Any php I put in there is escaped).

So, in short, how can add a hello world output to a page using a plugin (Stupid, but just to get me started)

My thought is that as soon as I can do that I can have a function that grabs form data from a previous page and processes it in order to do some real work.

Thank you so much for your help!

Andy


texts: Custom Fieldtype in a plugin at user profile save

texts:
I have made a custom fieldtype.

{% import "_includes/forms" as forms %}

{{ forms.textField({
    label: "business"|t,
    required: true,
}) }}

And added it to the user fields.
Where do I need to save data entered in at a user profile.

I would like to hook into the onSaveUser event with my plugin to save my values into the address model of Craft Commerce, but how would I do that?

An example would be appreciated.


texts: How can I convert a dropdown field value to an integer within a hash?

texts:
I'm setting up a twitter feed with craft.twitter.get() and I need to convert a dropdown value to an integer. Here is my code far:

{% set cacheTime = sidebarBlock.twitterFeedCacheTime %}
{% set tweets = craft.twitter.get('statuses/user_timeline.json?screen_name='~ sidebarBlock.twitterFeedUsername ~'&count='~ sidebarBlock.twitterFeedTweetCount ~ '&', { exclude_replies: sidebarBlock.twitterFeedIncludeReplies, include_rts: sidebarBlock.twitterFeedIncludeRetweets, }, {}, true, cacheTime) %}
{% if tweets %}

{{ sidebarBlock.twitterFeedTitle }}

  {% for tweet in tweets %}

      @{{ tweet.user.screen_name|raw }}: {{ tweet.created_at |nicetime('m-d-Y') }}

      {{tweet| tweetLink(newWindow='true') | raw}}

  {% endfor %}

{% endif %}

It seems that no matter what I try on twitterFeedcacheTime it returns a string to integer conversion error:

Object of class Craft\SingleOptionFieldData could not be converted to int

/craft/app/etc/cache/FileCache.php(85)

73      * @param  string  $value  The value to be cached
74      * @param  integer $expire The number of seconds in which the cached value will expire. 0 means never expire.
75      * @return boolean true    If the value is successfully stored into cache, false otherwise
76      */
77     protected function setValue($key, $value, $expire)
78     {
79         if (!$this->_gced && mt_rand(0, 1000000) < $this->getGCProbability())
80         {
81             $this->gc();
82             $this->_gced = true;
83         }
84
85         if($expire <= 0)
86         {
87             $expire = 31536000; // 1 year
88         }
89
90         $expire += time();
91
92         $cacheFile = $this->getCacheFile($key);
93
94         if ($this->directoryLevel > 0)
95         {
96             IOHelper::createFolder(IOHelper::getFolderName($cacheFile), IOHelper::getWritableFolderPermissions());
97         }


texts: Need help with filling matrix images into CSS grid

texts:
I want to fill in shuffled images into a CSS grid as a project overview. The images come from a matrix and have 4 different formats. So I want to fill in a format A image into the fitting grid cell (callA1, cellA2 ...). With my code, I have the problem, that the loop iterates over all items and fills all the A-sized cells with the same image. I would like to have image1 in cellA1 and image2 in cellA2 and image3 in cellB1 and so on.

{% for allProjects in craft.entries.section(['projekteZitate']).all() %}
   {% set shuffledProjects = shuffle(allProjects) %}

       {% for block in shuffledProjects.projekteMatrix %}
                    {% if block.type == 'A' %}
                         {% set image = block.A.one() %}
                             {% if image %}

                              {% endif %}
                    {% endif %}

                    {% if block.type == 'A' %}
                         {% set image = block.A.one() %}
                             {% if image %}

                              {% endif %}
                    {% endif %}

                    {% if block.type == 'B' %}
                         {% set image = block.A.one() %}
                             {% if image %}

                              {% endif %}
                    {% endif %}
        {% endfor %}
{% endfor %}


texts:
Can I use the free version of Craft for a portfolio site?  I know the free version of ee is for personal/non-profit sites only.

Thanks


texts: How to use localized categories properly?

texts:
I've setup a localized site (de/en) with custom routing for my categories (which are marked as translatable). I use a tag route for my categories which points to the same template as my structure. Everything seemed to work fine but then I realized that the custom filter (via relatedTo) also outputs entries that don't belong to the current category locale.

To make it clear I'll try to give a rough schemata of my setup (using Craft Pro 2.3.2640):

section projects:

has the entry url format:
  de -> projekte/{slug}
  en -> projects/{slug}
entry template path:
  projects/_entry

single projectsIndex:

has the entry url format:
  de -> projekte
  en -> projects
entry template path:
  projects/index

routes:

de -> projekte/(tag)
  template path: projects/index
en -> projects/(tag)
  template path: projects/index

category:

doesn't have a it's own url
category field is marked as translatable

category entries (german version and the english translation):

 - de -> kultur      en -> culture    | (resp. title and slug)
 - de -> industrie   en -> industry   | (resp. title and slug)
 ...

project entries:

 - Entry A:
     de -> category relations ['industrie', 'kultur']
     en -> category relations ['industry']
 - Entry B:
     de -> category relations ['kultur']
     en -> category relations ['culture']

template projects/index.html:

...
{% set _filter = tag|default(null) %}
{% set _category = craft.categories.slug(_filter) %}
...
{% for entry in craft.entries.section('projects').relatedTo(_category) %}
   ...

urls (here comes the trouble):

 - /projekte
     -> lists german version of 'Entry A' and 'Entry B'  (expected)
 - /en/projects
     -> lists english version of 'Entry A' and 'Entry B' (expected)

 - /projekte/kultur
     -> lists german version of 'Entry A' and 'Entry B'  (expected)
 - /en/projects/culture
     -> lists english version of 'Entry A' (NOT expected) and 'Entry B'

...'Entry A' on '/en/projects/culture' shouldn't show up just because there's the 'kultur' category attached to the german version of this entry!

I already tried to explicitly restrict the '_category' by using the '.locale' method but that didn't help either. Now I wonder if I'm doing something fundamentally wrong or if this is a bug by craft itself.

Any tips are appreciated.

Thanks

Update:
Answering my own question here.


texts: How to export 1 Entries type ("news") from Craft to Wordpress

texts:
I have a lot of News entries in a Craft 2.6.2990 website that I would like to export and then import into Wordpress.
Most of the advice out there is for doing this the other way round.
I need Title, Post content, featured image and date created for each entry.

I am thinking that I should be using the Sprout plugin to export to a csv file. Can anyone offer any advice on this and confirm if this is the right way to go about it? I am not very familiar with Craft.
Thanks in advance


texts:
Trying to upload images and get the following error

Upload failed for "filename". The error message was "Error uploading the file: The folder "/var/www/html/imgs/logos/" is not writable"


texts: Get "Internal Server Error Undefined index: handle"

texts:
Hi I was trying to save the matrix field and got the error:
"Internal Server Error

Undefined index: handle"

I checked out all fields' handles and they are all in place.

Is there any reason causing the error?

Thank you!


texts: Nested objects for geoJSON using Element API

texts:
I'm trying to create a GeoJSON feed using the Element API plugin but having difficulty creating the nested structure required for the JSON object:

{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [125.6, 10.1]
  },
  "properties": {
    "name": "Dinagat Islands"
  }
}

I can get a flat json structure using:

...

return [
    "type" => "Feature",
    "geometry" => "",
    "properties" => ""
];

...

My question is, how would I update the above code to create the nested json objects for geometry and properties?

Thanks. G.


texts: How to add custom fields for products in Craft Commerce and output them in the cart

texts:
You can add a note field for a product on the 'Add to Basket' form in Craft Commerce, and output this on the basket page using {{ item.note }}

So I'm using the note field field to record the page URL for the product, so I can link back to the product page for each line item in the basket.

However, I'd rather use a custom field or a dynamic field to do this instead. Is this possible? If so, how?

I've tried creating a dynamic field named 'test-page-url', but that didn't work when trying to output {{ item.testPageUrl }} on the basket page. I got this error:

  Craft\Commerce_LineItemModel and its behaviors do not have a method or
  closure named "testPageUrl".

I also tried creating a new product field (productPageUrl) and using this name, but that didn't work either. I got this error when trying to use {{ item.productPageUrl }} on the basket page:

  Craft\Commerce_LineItemModel and its behaviors do not have a method or
  closure named "productPageUrl".

Thanks for any help in advance.


texts:
I'm relatively new to Twig and PHP in general, so please don't shoot me just yet for asking stupid questions!

Basically, I've got several feeds from RSS to Facebook and Twitter. And I need to merge all of these into a custom array so I can make sure all fields match. I'm gonna output all these later, after sorting them by their published date.

But how do I get started with this thing? Create an empty array first, and then loop through the feeds and push each post into the array? How do I name the fields? This is what I have so far:

{% set feeds_array = [] %}

{% set feed = craft.feedme.feed(my_rssfeed) %}

{% for node in feed %}
    {% set feeds_array = {'title': node.title} %}
{% endfor %}

{% for post in feeds_array %}
    {{post}}
{% endfor %}

Is this the way to go about this?


texts: Is it possible to send the Password reset email via SMS instead of email? I'm signing users up using their mobiles and a 6 digit pin + a randomly generated email.


texts: Two domains, one server with Craft installed

texts:
I already have Craft running on a single domain name successfully.

For my client, we've bought a second domain name for a mini site for SEO purposes, some of which we'd like to use Craft on.

What are my options?

I'd like to try to use the same Craft login to manage both sites for the client. The site uses almost identical resources, it would just need a different index page and unique named pages.

Or do I have to go down the vhosts route?

Any help appreciated.


texts: Has anybody integrated craft with a rewards system?

texts: Just wondered if anybody had done anything like this? Perhaps through zapier or a custom inetgration? Customers earning points or discounts through a Craft e-commerce site?


texts: Sprig - Filter entries by custom field checkbox values, separate values as well as all values

texts:
I am having a question regarding Sprig.
I do want to filter my entries for values that are defined in a dropdown field (example below is simplified).
It does work to the point where I want to filter all entries for all values, on page load all single checkboxes should be checked as well as the all checkbox.
The problem is that Sprigs AJAX request sends a single request for each single filter e.g.:
dropdown_field[]: dropdown_value_1
dropdown_field[]: dropdown_value_2

but for the all filter, and e.g. one checkbox it will be:
dropdown_field[]: dropdown_value_1, dropdown_value_2 .....
dropdown_field[]: dropdown_value_2

Unchecking the all checkbox will not empty the array, what it should.
That will cause the single filters not to work if all is checked. How can I make sure that the query request will be one array for all values instead of multiple query requests?
All Filters should be activated on load, the all filter would be disabled then. If a single checkbox is checked all shouldn't be checked (array has to be empty except the single value).
{% set dropdown_field = ['dropdown_value_1', 'dropdown_value_2', 'dropdown_value_3', 'dropdown_value_4', 'dropdown_value_5'] %}

{% set entryQuery = craft.entries({
    dropdown_field: dropdown_field,
    section: 'section_1',
}) %}

        <input sprig type="checkbox" name="dropdown_field[]" id="dropdown_value_all" value="" {{ dropdown_field|length >= 5 ? 'checked disabled' : '' }}>

            Select All Values

    {% for value in dropdown_field %}

        <input sprig type="checkbox" name="dropdown_field[]" id="{{ value }}" value="{{ value }}" {{ value in dropdown_field ? 'checked' : '' }}>

            {{ value }}

    {% endfor %}

    {% for entry in entryQuery %}

{{ entry.title }}

    {% endfor %}

Thank you!


texts: Cache HTTP and HTTPS seperately using {% cache %}

texts:
we have a page that can be accessed both via regular HTTP and HTTPS. We now stumbled across an issue that if a page has been loaded via HTTP (and the content has thus been cached) and another user tries to load the same page via HTTPS afterwards, the browser complains about loading non-secure content, as Craft serves the cached content (e.g. URLs to images) that was generated while accessing the page via HTTP.

Shouldn't the {% cache %} tag take the protocol into account when comparing URLs?
Is there a known workaround or best practice for handling this?

Thanks,

Clemens


texts: How do you save custom fields on an EntryFixture?

texts:
I can't for the life of me figure out how to setup EntryFixtures in craft to populate with custom fields. I'm using the project config which already has the sections and fields defined in my tests. I'm trying to set a field, gmbId, that's set on a locations entry type. Here's my code. I feel like I'm missing something basic here.
codeception.yml
actor: Tester
paths:
  tests: tests
  log: tests/_output
  data: tests/_data
  support: tests/_support
  envs: tests/_envs
bootstrap: _bootstrap.php
params:
  - tests/.env
modules:
  config:
    \craft\test\Craft:
      configFile: "tests/_craft/config/test.php"
      entryUrl: "http://host.docker.internal/index.php"
      projectConfig: {
        folder: "config/project",
        reset: true
      }
      migrations: []
      plugins: []
      cleanup: true
      transaction: true
      dbSetup: { clean: true, setupCraft: true }

LocationFixture.php
<?php

namespace tests\fixtures;

use craft\test\fixtures\elements\EntryFixture;

class LocationFixture extends EntryFixture
{
    public $dataFile = __DIR__ . '/data/locations.php';
}

locations.php
<?php

return [
    [
        'sectionId' => $this->sectionIds['locations'],
        'typeId' => $this->typeIds['locations']['locations'],
        'title' => 'Location 1',
        'gmbId' => '123' # this is the custom field I'm trying to set.
    ],
    [
        'sectionId' => $this->sectionIds['locations'],
        'typeId' => $this->typeIds['locations']['locations'],
        'title' => 'Location 2',
        'gmbId' => '123'
    ],
    [
        'sectionId' => $this->sectionIds['locations'],
        'typeId' => $this->typeIds['locations']['locations'],
        'title' => 'Location 3',
        'gmbId' => '123'
    ]
];


texts:
In Craft 3, I've got a service function that I'm passing either an 'entry' or 'category' element into.

I'd like to know how to differentiate between the possible element types; This kinda of works:

public function getElementType($element) {
  if ( isset($element->group) ) {
    return = 'category';
  } else if (isset($element->section)) {
    return = 'entry';
  }
}

However I can't help but feel this is unreliable and hacky. Is there a better way to check an elements elementType?


texts:
On my site I have some entries with images. In the entry template I paginate the images like so:

{% paginate entry.images.limit(1) as images %}

My homepage is a single random entry and I want to paginate it as well. The Problem is, paginate expects an elementcriteriamodel, not an array. So this doesn't work:

{%
set project = craft.entries()
    .section('projects')
    .orderBy('RAND()')
    .with([
        ['images', { withTransforms: 'width' }],
        ['category']
    ])
    .one() %}
{% paginate project.images.limit(1) as images %}

I tried this, but that somehow doesn't work in Craft 3.

{% set queryParams = {
    with:[['images', { withTransforms: 'width' }],['category']]
}
%}

{%
set project = craft.entries(queryParams)
    .section('projects')
    .orderBy('RAND()')
    .one() %}

{% paginate project.images.limit(1) as images %}

Any solutions?


texts:
I know there are some similar questions out there but none of the solutions suits my needs.

What I'm trying to do is to display some related entries (from another section) within my blog posts.

Here is what I have right now. Not working (obviously, it's me :))

{% for entry in craft.entries %}
    {% for block in entry.matrix %}
        {% if block.type == "body" %}

                {% for recipe in craft.entries.section('recipes').search('block.body:pizza').order('score') %}
                    {{ recipe.title }}
                {% endfor %}

        {% endif %}
    {% endfor %}
{% endfor %}

Please advise.