Best method to handle %20 in tag URLs with multiple words

Update.

After looking at the tag model a little more closely, it looks like tags have both a title and slug — so if you use the slug to construct your url then you shouldn't have that problem.

For your tag index:

    {% for tag in craft.tags.order('title') %}

{{ tag.title }}

    {% endfor %}

In your tag index page (assuming you are using the tag token in your custom route):

{% set tagEntry = craft.tags.group('myTagGroup').slug(tag).first %}
{% set entries = craft.entries.relatedTo(tagEntry).order('title').limit(null) %}


Can't save entries with dynamic subfolder path in Matrix

I figured it out -- I'll leave the question up in case anyone else runs into the issue.

I had Assets fields in my Matrix, but I also had a SuperTable field in the Matrix which contained an image. That was the one causing the error. Changing the subfolder path to {owner.owner.section.handle} solved the problem.


Category archive page isn't filtering by current category

Mystery solved; the relation code was too general; some of the entries were related to the category on the homepage, and the example code doesn't care about how or where the entries are related to the category as long as they are somewhere somehow.

I needed to be more specific:

{% set thingsToDo = craft.entries.relatedTo({
    targetElement: category,
    field: 'typeOfThing'
}) %}

Works.


Date conversion returning December for every single digit month representation

Here's what's happening... Every time you get "December", it's because the date is being parsed as December 31, 1969 (aka, just before the Unix Epoch). Basically, it's failing to parse the date properly, and thus defaulting back to the Epoch.

And here's why... date(key) is basically saying "Get the date of 4". Which obviously doesn't make any sense. So the "date of 4" is a fail, and you get the Epoch default instead.

So here's what I recommend instead... replace this:

{% set monthName = date(key) | date('F') %}

... with something more like this:

{% switch key %}
    {% case 1 %}
        {% set monthName = 'January'|t %}
    {% case 2 %}
        {% set monthName = 'February'|t %}
    {% case 3 %}
        {% set monthName = 'March'|t %}
    {% case 4 %}
        {% set monthName = 'April'|t %}
    {% case 5 %}
        {% set monthName = 'May'|t %}
    {% case 6 %}
        {% set monthName = 'June'|t %}
    {% case 7 %}
        {% set monthName = 'July'|t %}
    {% case 8 %}
        {% set monthName = 'August'|t %}
    {% case 9 %}
        {% set monthName = 'September'|t %}
    {% case 10 %}
        {% set monthName = 'October'|t %}
    {% case 11 %}
        {% set monthName = 'November'|t %}
    {% case 12 %}
        {% set monthName = 'December'|t %}
{% endswitch %}

That's a big chunk of code, I know. So feel free to offload that to a macro if it's more convenient.

Alternately, you could use a placeholder date, as carlcs suggested in his answer.


If i'm not mistaking, craft.request.getQuery() returns an array filled with all $_GET key-value pairs, so in your case:

{% set queryParams = craft.request.getQuery() %}

will let you do:

// Do with it what you like ...
{% set queryParams = queryParams | without(key) %} // Removes a param
{% set queryParams = queryParams | merge([{ 'limit' : 10 }]) %} // Adds a param
{% set queryParams['order'] = 'price' %} // Changes a param

After doing what you need to do, you can rebuild the query string:

{% set queryString = '' %}
{% for key, value in queryParams %}
    {% set queryString = loop.first ? '?' ~ key ~ '=' ~ value : '&amp;' ~ key ~ '=' ~ value %}
{% endfor %}
{% redirect(siteUrl ~ queryString) %}


Performance of a categories list with post count

I don't think you'll be able to avoid the database queries, but you'll definitely want to use cacheing here, and set a high cache time if possible.

Wrap your code in {% cache %} tags like below:

{% cache globally for 1 month %}
{% nav category in craft.categories.group('...') %}
   {% set entryCount = craft.entries.relatedTo(category).total() %}
   {{ category.title}} ({{ entryCount }})
{% endnav %}
{% endcache %}

If this navigation appears on every page, use the "globally" tag.


Are you looking for something like this? The second example will ensure an address variable exists, even if it is set to null.

{% set address = craft.commerce.customer.address(addressId) %}

or

{% set address = address is defined ? address : null %}

As for accessing the data, you would just do this:

{{ address ? address.firstName : '' }}

Another way to do it (without needing to define a null address variable) is:

{{ address.firstName ?? '' }}


There's a plugin that you can use to find unused assets: Asset Usage
This gives you an extra column in the Assets listing to indicate if an asset is used or not. Unfortunately, the Craft 2 version doesn't have the console command to delete all unused assets that the Craft 3 version does, but this may help you anyway.


Users in odd state of pending and needing password reset

Yeah... sounds like a registration workflow issue.  If they click on the activation link and it's past the time it's valid, the page does have a link where they can resend it, but that's only going to be helpful if they got the email in the first place.

I think for now you'll have to use the "Resend Activation Email" button in the CP.


Asset Upload via Plugin - S3 gets wrong Content-Type

While Craft 3 will be smarter about this, this is not currently possible in Craft 2.

What you can do, though, is modify craft/app/helpers/IOHelper.php::getMimeType() function so that it always returns the mime type by extension instead by the content, since the core problem is that FileInfo extension cannot detect JSON by looking at the file contents. I'm a bit doubtful of any future releases for Craft 2 that affect this file, but, for posterity, probably better to write down any changes you make somewhere in case they get reverted.


Locale Switch not Affecting News Index Template

This Google+ thread may help: https://plus.google.com/116942350387086245334/posts/TBtR3XwuZGx

Current options as per above thread:

Create a Single for the News index template
Create a localized template as per http://buildwithcraft.com/docs/templating-overview#template-localization


You could try this

{% set featured = craft.entries.section('blog').featured(1).count() %}
{% paginate craft.entries.section('blog').limit(12) as entriesOnPage %}
{% for index, entry in entriesOnPage %}
    {# entry is featured or it's the first entry and there are no other
    featured entries #}
    {% if entry.featured or (index == 0 and featured == 0) %}
        [markup A]
    {% else %}
        [markup B excluding featured item]
    {% endif %}
{% endfor %}


Dynamically specify the 'To' email/recipient using Contact Form plugin

Reading the documentation it sounds like you should be able to specify toEmail using a text input. I'm guessing that it is using the default email because you aren't validating the email address first.

<input type="text" name="toEmail">

The plugin will get toEmail from the post request and validate it for use.

$toEmail = craft()->request->getPost('toEmail');
$toEmail = craft()->security->validateData($toEmail);


Is "Replace file" a potential security hole?

The problem here again is that I cannot restrict the intern to his folders only; he can see all the Asset folders and can replace any file -- either through malice or incompetence.

Unless I'm missing something you want to be able to jail a user to only his folders?

I just tried this. While jailing a user to his own folder site wide isn't (currently) possible, what you're doing should be working;  you have to do that on a field-by-field basis. Make sure you're jailing the the right field?

When your intern goes to edit an entry, he shouldn't be able to replace an asset file in another folder if he doesn't have upload permission in the asset's source folder.

Make sure only his asset source is checked.  For example: I created 2 asset sources: Intern Images and Images.  As you mentioned, the only folders the intern can view and upload is  Intern Images; everything else is unchecked.

To test, I made a sample entry with my admin user and selected a PDF in a source that the intern user doesn't have access to. When I go to edit that entry as my Intern user, I can see the other assets in that folder—unless I've jailed it to a single folder—but I can't replace the actual asset because I don't have upload permission on that asset source. I can of course swap the asset for something else but the original asset FILE (the PDF's content) is left untouched.

If you're asking about replacing files that the Intern has access to as well, that's a whole other bag of worms and IMO trust issues. Security is a 2-way street.

However, I wonder if you could write a plugin to intercept the upload request and rename it before Craft has a chance to fire the "would you like to replace the file" so you always have a unique file name? IMO that gets touchy because you start to have 2 or 3 different versions floating around and that ends up causing even more stress.

Practically speaking, WordPress actually does this by default (appending -1, -2 to a file) and in my experience, it can drive users crazy. If you upload a file and you realize you have a typo or some part of your image still needs work after approval—and that file path is already linked from a couple spots on the server—you end up deleting the file and then reuploading again. Craft's method of asset management is so much better in this respect. But with great power comes great responsibility, as they say.


Not able to see the page Create your Account

You or the person who setup your system created an user account. See step 5 in the installation documentation (http://buildwithcraft.com/docs/installing). Therefore there should be an account and you could try to reset the password.

If you have access to the DB directly you could get or set the email/username associated to that account. Another option would be to start with a fresh installation.


I have used the placid plugin to achieve this in the past.
Is this what you are looking for?

https://github.com/olivierbon/Placid/wiki/Making-requests


The only thing I can think of off the top of my head is create custom routes in a plugin dynamically generated from your entryTypes, sectionHandles, and sectionHandle/entryTypes and then point them all to the same template, which would then either display the entries directly (via twig) or dynamically include a corresponding template, based on the handle.

Something like the following perhaps? Completely untested.

public function registerSiteRoutes() {

    // array to store routes
    $routes = [];

    // get all section and entryType handles
    foreach(craft()->sections->getAllSections() as $section)
    {
        // add '/sectionHandle' routes
        $sectionHandle = $section->handle;
        $routes[$sectionHandle] = array('_dynamicTemplates/routeHandler.html');

        foreach($section->getEntryTypes() as $entryType)
        {
            // add '/entryTypeHandle' routes
            $entryTypeHandle = $entryType->handle;
            $routes[$entryTypeHandle] = array('_dynamicTemplates/routeHandler.html');

            // add '/sectionHandle/entryTypeHandle' routes
            $routes[$sectionHandle.'/'.$entryTypeHandle] = array('_dynamicTemplates/routeHandler.html');
        }
    }

    return $routes;

}

The one thing I don't know is if 'registerSiteRoutes()' gets called on every request, or only once when the plugin gets installed. If not, then you may also need to call it directly from an 'init()' method (or maybe just anytime an entry is saved - so it doesn't get fired on every request).

public function init() {
    parent::init();
    self::registerSiteRoutes();
}

The template would then grab the segments, perform an ECM search, and display results (or include a dynamic template based on the segments). Note: you might need to add an 'all' (or something else) to the solo 'entryTypeHandle' routes if there is any chance that your sectionHandle and entryType handles are the same. (i.e. '/all/entryTypeHandle').

In theory anyway — the whole thing might not work also. Be interested to hear how it goes.

Note: there also may be some problems with my routes array. I've never tried creating a dynamic route to a template in this way (might need to explicitly add '/templates/'). If anyone sees a problem please feel free to edit the answer or leave a comment. Thanks.

Update: I see a potential problem. See this answer for possible solution. Not sure how to integrate it as part of the answer though. Perhaps send all requests to a controller action, and render the template from there. May have to leave it to you to try and resolve for now — sorry about that.


Do you have separate index.php files for your locales? There is a nicely explained documentation for this on the official Get Help pages: "How do I show localized content on the front end?"


Case sensitive craft.entries.search() in Craft

My answer in that other question was wrong (I've updated it).

As you pointed out, Craft normalizes all search keywords to be lowercase.  Case  sensitive searches would rely on the database's underlying collation if Craft didn't do that normalization first.

Probably worth adding as a feature request, if you think that shouldn't be the default behavior.


Batch saving a custom field to multiple users via controller

For such large amounts of operations it's best to use a Job. You should only make sure to batch your results and don't fetch every user separately.

use Craft;
use craft\base\Element;
use craft\db\QueryAbortedException;
use craft\elements\User;
use craft\helpers\App;
use craft\queue\BaseJob;
use yii\base\Exception;

class ResaveUsers extends BaseJob
{
    // Properties
    // =========================================================================

    /**
     * @var int[] The user Ids
     */
    public $userIds;

    /**
     * @var string the reference number
     */
    public $refNumber;

    // Public Methods
    // =========================================================================

    /**
     * execute
     *
     * @param \craft\queue\QueueInterface|\yii\queue\Queue $queue
     *
     * @throws \Throwable
     * @throws \craft\errors\ElementNotFoundException
     * @throws \yii\base\Exception
     *
     * @author Robin Schambach
     * @since  07.05.2019
     */
    public function execute($queue)
    {
        $query = User::find()->id($this->userIds);

        $totalElements = $query->count();
        $currentElement = 0;

        $elements = \Craft::$app->getElements();

        try {
            $i = 0;
            foreach ($query->each() as $user) {
                $i ++;
                $this->setProgress($queue, $currentElement++ / $totalElements);

                $tableValue   = $user->getFieldValue( 'aktionsRefNumber' );
                $tableValue[] = [
                    'col0' => $this->refNumber . '-' . $i,
                ];
                $user->setFieldValue( 'aktionsRefNumber', $tableValue );

                /** @var Element $element */
                $user->setScenario(Element::SCENARIO_ESSENTIALS);
                if (!$elements->saveElement($user)) {
                    throw new Exception('Couldn’t save element ' . $user->id . ' (' . get_class($user) . ') due to validation errors.');
                }
            }
        } catch (QueryAbortedException $e) {
            // Fail silently
        }
    }

    // Protected Methods
    // =========================================================================

    /**
     * @inheritdoc
     */
    protected function defaultDescription(): string
    {
        return Craft::t('app', 'Resaving {class} elements', [
            'class' => App::humanizeClass(User::class)
        ]);
    }
}

You can start your job with

Craft::$app->getQueue()->push(new ResaveUsers([
     'userIds' => [1,2,4,5,6],
     'refNumber' => 'foobar'
]));


Yup! The Control Panel Nav plugin is exactly what you're looking for.

It allows you to easily rename, rearrange, or hide any of your tabs. It also lets you create additional custom tabs, using any URL you want.


Query for entry related to current entry in section URI settings

Your will need to set up a route for the entry1 section.

For example, if your entry1 uri is looke like entry1section/{slug}, and your template is like "_entry1section/index" then the route would be

entry1section/{slug}/* to "_entry1section/index"

Then in the template, using

{% set lastSegment = craft.request.getLastSegment() %}
{% set all_slug_in_entry1_section = someFunctionToRetrieveSlug() %}
{% set all_slug_in_entry2_section = someFunctionToRetrieveSlug() %}

{% if lastSegment in all_slug_in_entry1_section %}

  {# means your request url is {siteUrl}entry1section/{slug} #}
  {# display the content from entry1 #}

{% elseif lastSegment in all_slug_in_entry2_section %}

  {# means your request url is {siteUrl}entry1section/{entry1-slug}/{entry2-slug} #}
  {# display the content from entry2 #}

{% else %}

  {% redirect '404.html' %}

{% endif %}


Craft::$app->elements->on(Elements::EVENT_BEFORE_SAVE_ELEMENT, function(ElementEvent $e) {

    // Make sure it's an entry.
    if ($event->element instanceof \craft\elements\Entry) {
        $entry = $event->element;

        // Check if it's in the section you care about
        if ($entry->sectionId == 1) {
            // Do your custom logic
        }
    }
});


Local vs Amazon S3 asset paths in multi-environment config

We created a plugin to help solve this problem:
https://github.com/Firstborn/Craft-CMS-Environment-Settings

This plugin allows you to specify different configurations per environment on a single asset source.


Business Logic Controller for Validating Address in Commerce

You can move it all into a Service and then call it from your main plugin file if you find it is getting unwieldy.

file: craft/plugins/businesslogic/BusinessLogicPlugin.php:

class BusinessLogicPlugin extends BasePlugin
{
    public function init()
    {
        craft()->on('commerce_addresses.onBeforeSaveAddress', function(Event $event)
        {
            craft()->businessLogic_events->onBeforeSaveAddress($event);
        });
    }
}

file: craft/plugins/businesslogic/services/BusinessLogic_EventsService.php:

class BusinessLogic_EventsService extends BaseApplicationComponent
{
    public function onBeforeSaveAddress(Event $event)
    {
        $address = $event->params['address'];

        if (empty($address->firstName))
        {
            $address->addError('firstName', Craft::t('Please enter your Name'));
            $event->performAction = false;

            // ...
        }
    }
}

Because $event is an object it will be passed by reference, and you don't need to return anything.


Embedding video using Craft 3 'Video Embedder' plugin

Worked it out - just needed to use the right syntax, for example:

{% set embed = craft.videoEmbedder.getEmbedUrl(entry.videoEmbed) %}

{% if embed | length %}

{% endif %}


Based on the official documentation the log files are under /storage/logs and look for the web.log file especially.

If you don't find anything check your webserver logs.


Craft 3 / Commerce 2 + Multisite & COMMERCE_PAYMENT_CURRENCY

It seems the const COMMERCE_PAYMENT_CURRENCY isn't checked and set inside Commerce 2 (It was in Commerce 1)

So I created a PR for this issue:

https://github.com/craftcms/commerce/pull/999


getDirtyAttributes() not showing changes

Entries are currently the only element type which support that method fully.


How to control the format of an asset's Title

For Craft 2, You can write a plugin that listens to the onBeforeSaveAsset event, and changes the title from the asset parameter to whatever you want. Something like:

if ($event->params['isNewAsset])
{
    $asset = $event->params['asset']
    $asset->getContent()->title = 'My New Title';
}

For Craft 3, you can write a plugin that listens to the BEFORE_HANDLE_FILE event like so:

Event::on(Asset::class, Asset::EVENT_BEFORE_HANDLE_FILE, function(AssetEvent $event) {
    $asset = $event->asset;
    $asset->title = 'My New Title';
}


Guest Entries plugin - set parent entry if using section

The Guest Entries plugin checks for a parentId value in POST and passes that on to saveElement, so that should be all you need to do: https://github.com/craftcms/guest-entries/blob/v2/src/controllers/SaveController.php#L216


Creating a guest entry, with a Matrix field, using Ajax

Answer to my question. I ended up making a form and printing out the post as JSON.

$('#submitQuiz').on('click', function (e) {
  e.preventDefault();

  var testEntrySubmission = [
    {
      name: 'action',
      value: 'guestEntries/saveEntry'
    },
    {
      name: 'sectionId',
      value: '5'
    },
    {
      name: 'enabled',
      value: '1'
    },
    {
      name: 'redirect',
      value: '/'
    },
    {
      name: 'title',
      value: 'user name'
    },
    {
    'name':'fields[answers]',
    'value':''
    },
    {
      'name':'fields[answers][new1][type]',
      'value':'6'
    },
    {
      'name':'fields[answers][new1][enabled]',
      'value':'1'
    },
    {
      'name':'fields[answers][new1][fields][question]',
      'value':'John Smith'
    },
  ];

  $.post('http://mywebsite.dev/', testEntrySubmission, function(response) {
    if (response.success) {
      console.log('success')
    } else {
      // response.error will be an object containing any validation errors that occurred, indexed by field name
      // e.g. response.error.fromName => ['From Name is required']
      alert('An error occurred. Please try again.');
    }
  });
});


This probably isn't the answer you need but what features are you actually needing it to do? Affiliate systems can range the gamut from simply dropping a cookie to tracking commissions.
Even a very basic system using coupon codes tracked in Craft Commerce could technically be considered an "affiliate" program. (Coupon codes happen to be relatively reliable since they hold up across devices, cookies etc.)
I've done a bit of this before, when a request comes in that has the UTM or whatever parameters you need, you set a cookie on the request. When someone checks out, you can check for the cookie and set a custom field on the order.
Seeing as Craft is pretty flexible, it's also possible you may also want to consider an out-of-the-box system that works in conjunction with Craft.


From your code example, it looks like you have several potential issues.  I'll outline them here and might need to revise this answer after you provide an update on how these things pan out.

It's unclear if you are trying to do this on an individual blog post page that has the entry variable already available to the template or if you are trying to do something more complex. If this is individual blog page as you mention in your comments the entry variable should already be available for you and you may need to remove the for loop ({% for entry in craft.entries %}) you have wrapped around your Matrix field code which is trying to loop through all your blog entries. On an individual entry page in a Section with URLs enabled, you can access your matrix field directly using entry.matrixHandle.

{# You can probably remove this wrapping for loop #}
{% for entry in craft.entries %}

  {# You can start looping through your matrix here #}
  {% for block in entry.matrix %}

    {# This is good, you want to make sure you are within the
       block you are trying to access #}
    {% if block.type == "body" %}

      {# I've moved your SEARCH code below so we can focus on it a bit more easily. We'll put it back here afterwards. #}

    {% endif %}
  {% endfor %}

{# You can probably remove this wrapping endfor loop #}
{% endfor %}

It looks like you also may have the wrong syntax or approach for your search query (.search('block.body:pizza')).  You're right that you can dynamically pass content to the search parameter within your matrix loop but:

You are trying to pass data from a Rich Text field which will not have a single word, but a whole bunch of words and not make for a very specific search.
Your syntax is incorrect.

Try simplifying your search to something hard coded that you know exists to get this to work.

craft.entries.section('recipes').search('pizza')

If that works, they you need to sort out how to pass a more specific dynamic variable.  I don't think this is going to work from your body field, but it could work from a more targeted field.

craft.entries.section('recipes').search(block.keywordField)

In this second example, I'm passing the variable directly, not wrapping it in quotation marks.  And I'm targeting a field called 'keywordField' that just has the word I want to search for not a big paragraph of text.

Alternatively, you may not be trying to search for a keyword available in your Matrix, and you may just be trying to find related content in your Recipes section to your blog post using a Entries Relations Field.  If this is the case, you may not need the search parameter at all, but relatedTo instead.

craft.entries.section('recipes').relatedTo(entry)

In the end, you're loop may look something like this:

{% for block in entry.matrix %}

  {% if block.type == "keywordField" %}

    {# Using a more targeted keyword field for the search #}
    {% for recipe in craft.entries.section('recipes').search(block.keywordField).order('score') %}
        {{ recipe.title }}
    {% endfor %}

  {% endif %}

  {% if block.type == "body" %}

    {# Pulling in entries from an Entries Relations field #}
    {% for recipe in craft.entries.section('recipes').relatedTo(entry) %}
        {{ recipe.title }}
    {% endfor %}

  {% endif %}

{% endfor %}


Get all orders which contains a certain product type

You're close. Products themselves aren't Purchasebles.

However, Variants of products are. And you can have more than one Variant of a Product.

So, we need to get all Variants of a particular Product type and then feed your query:

{# get products of a certain type #}
{% set productIds = craft.products.type('classes').ids() %}

{# get the variants from those product Ids #}
{% set theVariants = craft.variants.productId(productIds).all() %}

{# grab orders #}
{% set orders = craft.orders.completed(true).hasPurchasables(theVariants).limit(null).all() %}

You'll probably want to limit the orders returned at some point depending on how you're displaying or querying them.


Craft Commerce 2 — Remove Line Item (and other actions)

Is it as simple as changing the input to a submit (or button submit)
  using the same name tag contents?

Yes.

  Would this then also carry over to be posted via ajax in the same way
  as an update-cart action?

Yes.

Everything can be done on a single line item basis to the update-cart acton, just use the new param names.


How do I return ALL entries that are singles

There's no such method available for craft.entries, at least it's not documented. But you can use craft.sections to get an array of section models and filter them with a conditional within a loop:

{# Get all Section #}
{% set sections = craft.sections.getAllSections() %}

{# Loop through all single sections #}
{% for singleSection in sections if singleSection.type == 'single' %}

    {# Get the first (and only) entry of that section #}
    {% set singleEntry = craft.entries.sectionId(singleSection.id).first %}

    {# Output #}
    {{ singleSection }}
    {{ singleSection.isHomepage() ? '(Home)' : '(not Home)'}}
    {{ singleEntry.dateUpdated.atom }}

{% endfor %}


Is is possible to add a bespoke Twig template loader?

When you call Craft's TemplatesService->getTwig()  (craft()->templates->getTwig()), the first parameter you can pass in is your custom template loader classname.

i.e. craft()->templates->getTwig('\My\Awesome\Plugin\TemplateLoader, array('my' => 'options')


Next/Previous Asset or Image within Entry

Given that your assets are within an entry, it seems that a gallery browsing mechanism may fit well. I'd suggest a javascript framework such as Fancybox: http://fancyapps.com/fancybox/

Alternatively and perhaps more in line with your specific question, have a look at this related thread: Best way to access getPrev and getNext asset fields


You want:

{% requirePermission("editSite:#{currentSite.id}") %}

The way you have it now, the permission it's checking is the literal string editSite: (currentSite.id) which no one will have permission for.

Edit:

Craft 3.1 doesn't store IDs anymore for permissions, instead it uses always the uids because of the project config. This is a breaking change for many existing projects so keep that in mind.

{% requirePermission("editSite:#{currentSite.uid}") %}

c.f.: Twig string interpolation


Autogenerate complex Date / Count based Title

Unless I'm missing something, you should be able to use the seq Twig function (docs) and use something like:
{{ 'now'|date('Ymd') ~ '-' ~ seq('now'|date('Ymd'), 3) }}

This would generate the format you need YYYYMMDD-NNN and reset the NNN every new day.
Sequences are stored in your sequences database table.


How to use Position Select in Matrix blocks?

You would typically just pop out a CSS class based on their selection.

So:

Just pop the value out into your markup, and then write the CSS to produce whatever effect you need


How to upload several images & automatically create an entry for each one?

I was going to suggest using the very handy Import plugin, but I see that it only supports entries, categories, and users. And unfortunately, I don't see another plugin that does this specifically. But have a look at the craft plugins page in case I missed something.

You might also be able to extend the Import plugin (with permission of course) to support assets. I would guess that it would be a similar process. This could potentially allow you to create a CSV file and import it... then upload the images into the location defined in your csv.


How to disable plugin Disable and Uninstall?

This can be easy, write a module which can't be disabled or uninstall. See what's difference between module and plugin https://docs.craftcms.com/v3/extend/#modules-vs-plugins or https://nystudio107.com/blog/enhancing-a-craft-cms-3-website-with-a-custom-module


You might have seen Passing Multiple Relation Criteria  in the docs

{% set entries = craft.entries.section('flightcompany').relatedTo([
    'and',
    { targetElement: models, field: 'partsModels.model' },
    { targetElement: parts, field: 'partsModels.part' }
]).all() %}

You can as well take a look at the Db::parseParam the and|or syntax is the same for this field


Twig comes with a last filter which you should be able to use, so with your entry.gallery  you can do:

{% set lastBlock = entry.gallery|last %}

Which will return the last element in the sequence, there's more info in the twig docs:

  The last filter returns the last "element" of a sequence, a mapping, or a string:

Twig last filter


Export more than 50 Freeform submissions (without a lot of scrolling)

Sprout Reports is a flexible reporting plugin that allows you to create custom queries and export the results as CSV.

You could write a custom report using the default Twig Template or Custom Query reports building a report using Freeform variables in your Twig templates or a MySQL query that queries the report Freeform content table directly.

If you'd like to give your users settings, such as which Form to export submissions from, you can add settings to a custom Twig Template report or write a custom integration to define settings and handle your query using PHP.


Can I add a billing address while updating the cart?

Yes, you can submit all updates to the cart in the one controller action commerce/cart/update-cart


Please do yourself a favor and don't do this  in Redactor. Find a solution with Matrix (and/or Super Table) to add things like this in-between your text blocks.


Saving entry from Sprout Forms into channel entry

As of Sprout Forms 0.8.4 this is not possible.  It is on our list to allow more customization over the form entries and how they are output on the front end so this will be possible in the future.  If you'd like us to prioritize this functionality, drop us a note and we're happy to have that conversation.

If you wish to save a Craft Entry after the Form Entry is saved, you're using the right Event above.  One thing you will want to be careful of is that the Sprout Forms $entry value is a SproutForms_EntryModel and the variable you need to pass to the craft()->entries->saveEntry($entry) method is a Craft EntryModel.

To do this you'll need some code to hand off the field values on the Form Entry to the field values on the Craft Entry:

public function init() {

    // Support Sprout Forms plugin
    craft()->on('sproutForms.saveEntry', function(Event $event) {

        // SproutForms_EntryModel
        $formEntry = $event->params['entry'];

        // Craft EntryModel
        $craftEntry = new EntryModel;

        // Map your Form field values to the Entry field values
        $craftEntry->fieldName = $formEntry->fieldName;

        craft()->entries->saveEntry($craftEntry);
    });

}

That said, this method feels pretty messy to me.  Duplicating data is a great way to create great pains for yourself down the road. If you're set on doing this on your own, I'd recommend to create a custom plugin with and a variable that queries the Sprout Forms data how you'd like.

{% set userFormSubmissions = craft.myCustomPlugin.sproutFormsQuery(userId) %}

When Sprout Forms gets around to adding this functionality, you can swap out your custom tag for the native Sprout Forms one and ditch the custom plugin.


Export database from control panel or Sequel Pro? What's the difference?

The difference in both size and speed is likely because Sequel Pro (and any other MySQL client) is likely using mysqldump, which is a native CLI command and highly optimized.

Craft can't rely on that for a variety of reasons (PHP might have have exec permissions, the account Craft uses to connect to the database might not have the permissions necessary to perform a backup, etc.)

So Craft has it's own fallback where it manually analyzes the database's DML and DDL and writes it out to a file.

Slower?  Yes.  Larger file size?  Yes.  More reliable for Craft?  Yes.

It is on our list somewhere to check if Craft has the ability to access mysqldump and use that, if not fall back to our current method.


What would be the best way to build an Ad rotator?

I built a plugin which does exactly this... Ad Wizard.

You can put your ads into groups, and add that group to your template like this:

{{ craft.adWizard.position('rightSidebar') }}

That code will automatically display a random ad from the group (unless it's disabled, expired, or over its maximum allowed impressions).

You can also target a single ad specifically, by referring to its ID number:

{{ craft.adWizard.ad(42) }}

The plugin also gives you built in ad tracking... You can add two chart widgets to your dashboard which will show you statistics on how your ads are doing.

If you need any help, feel free to contact support@doublesecretagency.com... All feedback, bug reports, and feature requests are welcome!


Explanation of how to link to a structure from a structure

I'll assume that 'watch' is a landing page in which you want to list out the various sermons from the sermons structure. In which case you can retrieve and display those in the 'watch' template using a for...in or a nav...in loop. For example:

{% set sermons = craft.entries.section('sermons').limit(null) %}

    {% nav sermon in sermons %}

{{ sermon.title }}

        {% if children %}
            {% children %}
        {% endif %}
    {% end for %}

In your 'sermons' section settings you can then set the top-level uri to be:

watch/{slug}

And the nested uri to:

{parent.uri}/{slug}

In this way, you can set the uri's to match up nicely, with the index page as 'watch' and the sermon entries as 'watch/sermon-parent-slug/sermon-slug'


List entries for a single tag from blog section

You were very close! You are looping through craft.entries.section('blog') which doesn't use your tag query. You simply need to loop through the results of your query which you've set in the entries variable.

You may want to grab your weddings tag using the tag's id or slug as .search will find any tag with the string 'weddings' in it.

It might also be a good idea to use the conditional to check entries is returning something first, before outputting it.

{% set tag = craft.tags.slug('weddings').first() %}
{% set entries = craft.entries.relatedTo(tag) %}

{% if entries|length %}
  {% for entry in entries.limit(5) %}
    {# get stuff #}
  {% endfor %}
{% endif %}


Apologies - resolved. Case sensitivity issue with variable (signUp not signup)


Cache not invalidated on publishing new entry

Not the answer you'd be hoping for but the advice I got was to create a plugin to listen and clear the cache when a new entry was published https://twitter.com/craftcms/status/541968671300911104


Slow saving when devMode false, but not while true

I cleared all caches and updated file index, and now everything runs smooth. No idea why, but it fixed the problem.


Craft Commerce: Validation on Address Fields

In Craft3 you can do it like this:

use Craft;
use craft\base\Plugin;
use craft\commerce\models\Address;
use yii\base\Event;

class Custom extends Plugin
{
    public function init()
    {
        parent::init();

        Event::on(Address::class, Address::EVENT_BEFORE_VALIDATE, function (Event $event) {
            $address = $event->sender;
            if (empty($address->address1)) {
                $address->addError('address1', Craft::t('app', 'Address Line 1 is required'));
                $event->handled = true; // stop other handlers for this event
            }
        });
    }
}


Something went wrong when processing the logo

There was a problem with the URL of the image.

The RebrandController class removes '?' querystrings from the URL but in my case I had a '&'. Removing that solved the issue and Brad has confirmed this fix has been rolled into the next release.


How html title is generated in entry index page in CP

it seems that first column of table view is special and is called here
which calls mentioned hook in question.


Using Craft for publishing an online magazine

I wouldn’t recommend creating a ton of Structure sections, because the administration workflows and UI are just not suited for having lots of identical sections.

Here’s a basic model of how you could organize this in Craft:

Create two Sections called Issues and Articles
Create an Entries field called Issue Articles, with the Articles section selected.
Edit your Issues section’s Entry Type, and add the Issue Articles field to its Field Layout.

Now, each issue will be represented by an entry within your Issues section, and each article will be represented by an entry within your Articles section.

Thanks to the new Inline Element Creation feature in Craft 2.5, you will easily be able to define new articles right from the Edit Entry page when creating/editing a new issue, via your Issue Articles field.


I got around this issue by looping through all fields that were of BaseElementFieldType re-setting them to their current value.

$fields = $entry->getFieldLayout()->getFields();

$referentialFields = array();
foreach ($fields as $layoutField) {
  $field = $layoutField->getField();
  if ($field->getFieldType() instanceof BaseElementFieldType) {
    $referentialFields[$field->handle] = $entry->{$field->handle}->ids();
  }
}

$entry->setContentFromPost(array_merge($referentialFields, array(
  'yourField' => 'yourValue'
)));

craft()->entries->saveEntry($entry);


The ID won't change in different locales, check this answer for reference: Craft 3 language switcher

You could also test it in your templates e.g. :

{% for locale in craft.app.sites.getAllSites() %}
    {{ craft.entries.siteId(locale.id).one().id }} : {{ craft.entries.siteId(locale.id).one().title }}
{% endfor %}


How to loop through matrix block fields and pull out handle and content?

I find accessing content like this pretty unintuitive, but I think you will need to use the Twig attribute method.  Hopefully the below can help keep you moving in the right direction.  I've simplified to just accessing the Matrix Field and I've made an assumption that you know the Matrix field handles you will want to access.

{% for fieldLayoutField in entry.getFieldLayout().getFields() %}
  {% set field = craft.fields.getFieldById(fieldLayoutField.fieldId) %}

  {% if field.type == 'Matrix' %}

    {# Dynamically access the Matrix Field on the Entry Model #}
    {% set matrixField = attribute(entry, field.handle) %}
    {% for block in matrixField %}

      {# Output your Matrix Field Handle #}
      {{ field.handle }}

      {# Output your specific fields content #}
      {{ block.fieldHandle }}

    {% endfor %}

  {% endif %}
{% endfor %}

You may also want to take a look at how Craft handles outputting Forms in the CP in the app/templates/_includes folder, starting with forms.html and reviewing the many related files.   Doing a task like this cleanly really requires a pretty deep level of abstraction if you don't want to make any assumptions about your variable names.


Saving/assigning User Group via a plugin

So it seems the only way to achieve this is to assign the user to the group, not the other way round (assign the group to the user).

So once my user has saved I can call following:

craft()->userGroups->assignUserToGroups($user->id, $groupId);


How does craft deal with Plugin databases when updating plugin versions?

Every time Craft notices that a plugin's version number has changed (I imagine quite near the start of every request,) it checks for any new Database Migrations in that plugin that might need running in order get the database schema caught up to the code. That link, and this one for database queries should be enough to get you started.


Searching against lightswitch should work. Make sure Use this field’s values as search keywords is checked in Settings → Fields → your field then run ./craft resave/entries --update-search-index to (re)index your values.


I think you need to add the fieldId() param to your query as per https://github.com/craftcms/cms/issues/1789


How do I differentiate between entries after merging an array?

Not sure if I totally got it but you can check the class of an object via

{% if element is instance of ('craft\\elements\\Entry') %}

or via switch statement

{% switch className(element) %}
    {% case 'craft\\elements\\Entry' %}


Template for Site Group rather than site handle

It's not ideal, but you can use one template folder for each group and then create symbolic links for all the language sites.


Using ImageOptimize, how do you loop through photos?

So the OptimizedImages field in ImageOptimize is added to your asset as a field (just like Entries can have fields), because it's added to your Asset Volume layout.

So you'd iterate through the images the same way you would iterate through any assets in Craft. I'm a little unclear on what part you're stuck on here? If you could clarify, I could help you more.

So let's say we have an Asset's field with a handle of heroImages, to output all of those images we'd do:

{% for heroImage in entry.heroImages.all() %}

{% endfor %}

So then let's say you have an OptimizedImages field with a handle of optimizedImages that's in your Asset Volume's layout, so it becomes a field that's in your Assets. Then we could just do:

{% for heroImage in entry.heroImages.all() %}

{% endfor %}

And it'll output all of the same images as in the previous example, but using an optimized srcset of the images.


Struggling with language switcher for Craft 3

I think I might finally have it working. If someone has a more elegant way to handle the index, tag and category I would love to see it!

        {% if entry is defined %}

            {% for siteForEntry in entry.getSupportedSites %}

                {% set site = craft.app.getSites.getSiteById(siteForEntry.siteId) %}

                {% if site.id != entry.siteId %}

                    {% set entryForOtherSite = craft.entries.id(entry.id).site(site).one() %}

                    {% if entryForOtherSite is not null %}

{{ site.name }}

                    {% endif %}

                {% endif %}

            {% endfor %}

        {% elseif category is defined %}

            {% set currentSite = craft.app.sites.currentSite %}

            {% set sites = craft.app.sites.getAllSites() %}

            {% for site in sites %}

                {% if site.id != currentSite.id %}

{{ site.name }}

                {% endif %}

            {% endfor %}

        {% else %}

            {% set currentSite = craft.app.sites.currentSite %}

            {% set sites = craft.app.sites.getAllSites() %}

            {% for site in sites %}

                {% if site.id != currentSite.id %}

{{ site.name }}

                {% endif %}

            {% endfor %}

        {% endif %}


FeedMe - all sites get overwritten by other foreign sites import, even though fields are translatable per group

This is expected behavior when importing Matrix blocks, currently. See my comment on craftcms/feed-me#463 for a full explanation and possible workaround.


How can I redirect HTTP to HTTPS with a local self assigned SSL certificate in my .htaccess?

The condition should be:

RewriteCond %{HTTPS} !=on

(You were missing the = sign.)

For more info, see our help article, How do I force SSL for CP requests?


I would like to offer another solution: We always  have a structured section pages where our clients can insert all the pages they want to show. It's a structured section because the menu is generated by this structure and they have certain options in these entries if they should appear in the menu/footermenu and so on.

Different Entry Types in this section have different templates, sometimes when it's required we create special field types to choose different templates as well. When the client wants to insert an "overview" page to display news he/she creates a new entry in our pages section with the entry type news that has a special template that fetches all latest entries in the news section and renders them.

That way we don't need to create a special rule and we don't need to create a single page -> thus we don't need to offer a special menu plugin. From the feedback we got from our clients they prefer this method because they have everything they need in this structured section and they don't need to create a separate menu or something like that. Dragging/moving these entries causes the menu to change and due to Craft it's very intuitive.

When it's required, we restrict the number of times certain entry types can be used. For example we only need one news overview or one login page. It does not make sense to create 3-4 different login pages so as soon as our client selects this entry type it disappears from the list and he/she can only create another login page after the first was deleted.

If you are interested: this is our default template for entries in the pages section

{% extends [
    'pages/_custom/' ~ entry.slug ~ '.twig',
    'pages/_entrytypes/' ~ entry.type ~ '.twig',
    'pages/_generic.twig'
] %}

Craft/Twig takes the first template that is found. _generic is the default content template


You don’t have the proper credentials to access this page

Be sure that you're testing as a logged-out user on the front-end of the site.  If you have an active Craft session, you could be getting a false positive error message.


To get the URL of an asset in a plugin, you use a similar technique as you do in twig, so this will fetch the URL of the first image in the blogImage field:

$picture = $entry->blogImage->first()->url;

To answer you second question, onBeforeSaveEntry is run just before the entry is actually saved, not just before it is published live on the site if it has been saved with a post date in the future.

Craft doesn't fire any events just before an entry becomes 'live' on the site, so if you want the post to Buffer to go out at the same time as the entry goes live using this technique, you will need to actually create and save the entry when you want to publish it live on your site.


Picking this up with another project, it looks like the problem was me not specifying a template path as the 'setPasswordPath' config setting. Instead, I was passing a route. I was doing this because I wanted to use the same password template to handle everything to do with passwords. This isn't possible, by the looks of it, because the controller is looking for the existence of a file (as opposed to a template being returned from a route or URI).

As soon as I changed it to a strict template path everything worked fine, and the following line in UsersController.php no longer returns false:

if (craft()->templates->doesTemplateExist($templatePath))

So this is solved.


'Invalid argument supplied for foreach()' using Shopfiy Craft Plugin

Turns out this was an issue with 'https://' being in the store's URL in the CMS.


I can't think of a super-easy way to figure this out off of the top of my head.

There are a couple of not-so-easy ways to figure it out, though.

1) Find the column in the craft_content (or the equivalent Matrix content table) and find all the rows with empty values.

2) From either a plugin (PHP) or a template (Twig), write some code that grabs all of the entries you are interested in and loops through them checking if the particular field has a value or not.


Any good tutorial for plugin developement? I am entirely lost

We just published a video course on Craft plugin development that might help you. https://mijingo.com/products/screencasts/craft-plugin-development/


How to exclude child elements when looping through categories?

Rather than preparing multiple queries - you can execute the Query in your field value

{% for category in craft.categories.group('categoryGroup').level(1).find() %}
    {% for resource in category.fieldHandle.find() %}
        {{ resources.title }}
    {% endfor %}
{% endfor %


You can replace a file directly in the control panel. Navigate to Assets, select the file you want to replace and then click the cog icon to select the “Replace file” action.


If you enable devMode, then memory usage, along with tons of other debugging information (# of database queries, query profiles, execution timestamps, etc.) will be output to your browser's console.


How do you list categories in a category group?

You can fetch your categories on the front end using craft.categories, which has a group param that can be used to filter categories by a given group handle.

{% set categories = craft.categories.group('myGroupHandle') %}

If the category group is limited to a single level, you can loop through those using a basic for-loop:

    {% for category in categories %}

{{ category.title }}

    {% endfor %}

If the category group can be multi-level, you might be better off using the {% nav %} tag instead:

    {% nav category in categories %}

            {{ category.title }}

            {# Output a nested
 if this category has any children #}
            {% ifchildren %}

{% children %}

            {% endifchildren %}

    {% endnav %}


Currently you are trying to compare objects with each other and of course they are always different since they have a different reference. entry.vendor is not a single selected value but the field with all it's options and possible values.

Please try

{% for entry in craft.entries.section('orderBook').order('vendor').all() %}
    {% if entry.vendor.value not in vendorArray %}
        {% set vendorArray = vendorArray|merge([entry.vendor.value]) %}
    {% endif %}
{% endfor %}


image.filename should work unless I'm missing something. Note that it is case-sensitive.

The documentation on AssetFileModel can be found here:
http://buildwithcraft.com/docs/templating/assetfilemodel


Change field arrangement from the entries page

No, that's not possible with Craft at the moment (2.4). You'll have to use the Field Layout Designer from Settings -> Sections -> {Section} -> {Entry Type} to manage your fields and tabs.

You could always add a feature request if you feel this is something that should be included in the core.


Linking to specific entries in Twig: How performant is Reference Tags parsing?

If you turn on debug mode in your config file, and then create an ultra simple template with just these code options in it, you should be able to look at the logs in the console. It should tell you the query time in milliseconds. I've never used reference tags; however, I  would suspect that the performance difference is minimal. I personally would opt for the second method, so that entry.title is not hard coded.

As a side note, you can also wrap the code in {% cache %}... {% endcache %} tags to further increase performance either way.


Show a child's Matrix within a Structure

This should do it, user2569

{% for block in entry.myMatrix %}
    {% if block.type == 'intro' %}
        {{ block.intro }}
    {% endif %}
{% endfor %}


Ok, I found this:
https://docs.craftcms.com/api/v3/craft-services-elements.html#method-getallelementtypes
Craft::$app->getElements()->getAllElementTypes()


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

After the page loads with the form loads, delete the CSRF cookie, then submit the form.  It should fail CSRF token validation.


How do I export search results as a csv?

You can just make link to a twig template to output a csv quite simply...just like any other template really, except it won't extend you layout etc. and will simply contain something like:

{%for result in results %}
    {{var1}},{{var2}},{{var3}} etc...
{% endfor %}

Depending on what sort of csv you're after and what you're going to do with the data, you may want to consider escaping the data as you output it:

http://twig.sensiolabs.org/doc/filters/escape.html

In terms of setting it up as a  link, your csv template could just accept the same search parameters passed through and essentially repeat the search and output the csv results as above.

I.e. in your original results page you could build the link to the CSV as

Get Results As CSV

And then in the csvmaker

{% set results = craft.entries.search(q).order('score') %}
...etc as above

But a lot depends on how you've built your search in the first place really.

If you want it to trigger an actual file download, then I've found that's pretty easy to do that on the front end with some JS, e.g. I use this:

https://stackoverflow.com/questions/19721439/download-json-object-as-a-file-from-browser/20343999


Check for errors (any) on guest entry form (Craft 3)

You can use this

{% if entry.hasErrors() %}
    Render a message here
{% endif %}


Prettiest way to loop through nested relations?

Would this work?

{% set teams = craft.entries.section('team').relatedTo(studios) %}

All teams in {{entry.title}}

{% for team in teams %}

{{team.title}}

{% endfor %}


How to keep the setPasswordPath config when reset password link is expired?

Pretty sure the invalidUserTokenPath config setting is what you're looking for.


Why do you want to let them register twice? Maybe re-think the way you go about this:

Possible solutions:

Add them to a certain user group (via a plugin) on registration with the appropriate permissions and/or...
...if you don't want to write a plugin, you can add a certain category to the user element on registration. You can than check throughout your site if the user has the correct category ('permission') to do something. If they come back and want to become a full member, just let them fill out a new form which UPDATES their already existing user account with a new category/permission.

That's the way I used it on a large site and it works rather fine.


https://github.com/ryanshrum/hacksaw

This hasn't been fully tested for production, or documented for that matter, but I have migrated it over and tested basic usage as per the docs on devot-ee. It should, at the very least, give you a nice start.

You can use the Twig filter with: {{ entry.fieldHandle|hacksaw(words="100") }}


What changes are needed if I change directory structure?

You have to define the path to Craft in your www/index.php file.

define('CRAFT_BASE_PATH', __DIR__ . '/../craft/' ); // <- in your case something like this

The constant CRAFT_BASE_PATH must point to your /craft folder


Don't have enough reps to comment - but it does not seem to be a Craft issue - but rather a Bootstrap modal issue. It seems like when you open the video, it updates the id of the video.

Based on past experiences - I would look into destroying the modal instance and reloading new content in one modal, as opposed to having multiple modal for multiple content.

Update: Just looked a little more into your code and how it's reacting - it seems like on modal close (of either modals), it updates the value of the video embed code to the varilift-lx video.

^ Caused by scripts.js - Line 2172 - 2174

$('.modal').on('hidden.bs.modal', function () {
    $('.video-container iframe').attr("src", $(".video-container iframe").attr("src"));
});

It is grabing the first video container and updating it to that value.


How do I remove segment 1 in my URL AND get the parent URI?

Edit your section‘s settings (Settings > Sections > [Section Name]), and delete the static/ from the Entry URI Format.


How to display all fields belonging to current entry?

Field groups are not specific to a particular channel or channel entry. They are just an arbitrary organization within the control panel for ease of use. What you would be looking for are the fields defined for the particular field layout for that entry. I.e.:

{# loop through the fields in the entries fieldLayout Model #}
{% for fieldLayoutField in entry.getFieldLayout().getFields() %}

    {# get the field Model from the fieldId #}
    {% set field = craft.fields.getFieldById(fieldLayoutField.fieldId) %}

    {# print the field handle and the field content  #}
    {{ field.handle }} : {{ entry.getContent()[field.handle] }}

{% endfor %}

By the way, there is an excellent plugin called 'Inspector' written by Adrian McNeal that displays all methods/attributes/properties of an object or variable, which can be very useful for figuring out what your dealing with.

UPDATE: It has been brought to my attention thatfieldLayoutField.fieldId has been discontinued in favor of fieldLayoutField.id. While not tested, if the above does not work, please try the following instead:

 {% set field = craft.fields.getFieldById(fieldLayoutField.id)


Upcoming events from specific groups using Venti

After looking at this for over an hour I've literally figured it out. Just in case others need it:

craft.venti.events.group('handle').limit(5)

So easy!


Migrating a whole website between Craft instances

Make sure both Craft installs are up-to-date.
Craft's license is saved in craft/config/license.key, make a backup of your purchased license file.
Move all your files/directories except:

  /craft/app/
  /craft/storage/

Copy the backup of your license.key to craft/config/.
Remove /craft/storage/, if it exists on your new server, to prevent cache errors.
"dump and load" your database to the new server. Craft will update what's necessary.
Update your config settings in /craft/config/.
Go to your BackEnd.

Also you might find this interesting:

What's the best practice for handling data migration and organization across development environments?


URL Structure - advise and thoughts of best approach?

I’d go for /hot-tubs/used etc

This way you can also have /accessories/pipes etc


Form fields not visible after creating content fields using A&M Forms plugin

As noted in the documentation for AM Forms the fields that are created for forms

  …are stored in a different context / scope than Craft's fields.

and that;

  …they won't be shown in Craft's field list.

I assume that the reverse is then also true, so fields created in Craft will not be visible in the plugin.


Get entries that are enabled and disabled for the site

With the help of Oli from Craft, it turns out the solution is simpler than I thought:
{% set items = craft
    .entries()
    .section('works')
    .anyStatus()
    .all()
%}

This returns all entries, enabled and disabled.


Guest Entries creating new entry instead of editing the current one

I got it to work by adding the below at line 182 of GuestEntriesController.php

        $entry->id = craft()->request->getPost('entryId');

Then I added a hidden field with the current entries id in the template.

<input type="hidden" name="entryId" value="{{ entry.id }}">

I don't know if this is the best way to do it but it seems to be working. If this is going to cause issuees or there is a better way to do it let me know and I will swap my fix out with yours.


Can I use translated properties for URL formats

This turned out to be easier than expected. It's not documented in the filters section of the docs, but the t() filter can take other parameters after the  tokenised variables you might want to replace in the string. Paraphrased from the source code of the globally available t() function:

source: Defines which message source application component to use. Defaults to null, meaning use 'coreMessages' for messages belonging to the 'yii' category and using 'messages' for messages belonging to Craft.
language: The target language. If set to null (default), craft()->getLanguage() will be used.
category: The message category. Please use only word letters. Note, category 'craft' is reserved for Craft and 'yii' is reserved for the Yii framework.

So, the solution was as simple as:

{type|t(null, null, 'nb')}/{slug} for URL format for Norwegian and

{type|t(null, null, 'en')}/{slug} for English.


Sorry, but the answer is no; assets will initially just get titles based on their filenames until someone goes into the Control Panel and customizes them.


Pulling categorized entries in a category loop

Have part of the solution which is to use:

{% set categories = entry.categoriesFieldHandle %}
{% if categories | length %}

Some great categories

{% nav category in categories %}
    {%for entry%}
    {%endfor%}

{% endnav %}
{% endif %}

Just now need to find out how to add the Category Title in and work on separating the entries out.


We at Familiar have decided to leave craft out of git because of this exact issue.  It's extra hassle every time an update comes out.

To better deal with it we've built a couple of grunt functions as part of our craft yeoman generator.  You can see the whole generator on npm: https://www.npmjs.org/package/generator-familiar-craft. Or just an idea of how the grunt tasks are setup: https://github.com/familiar-studio/generator-familiar-craft/blob/master/app/templates/Gruntfile.js

The tasks are pretty simple, the first one will download the latest copy of craft, unzip it and then move just the app folder into place (perfect if your local environment gets way behind)

We also have a database pull grunt task that grabs a copy of the live (or any staging) database and imports into your local database.

This way there's always a quick fix through one or both commands if things get out of sync on any of our developers local environments

So our normal update process is this

Update local to make sure everything's fine.
Update live
Celebrate!!
No committing needed.

Generally we treat craft just like any other project dependency manager like bower would and only add our own code to our repos


Correct syntax for an OR conditional within a Matrix block

As already noted by @Benjammin' in the comments, the or operator has to be lowercase. See Logic Expressions in the Twig docs:

  Operators are case sensitive.

You also have to get the dropdown value explicitly by accessing its value property.

{% if block.wellFormattedContent.value == 'toBeActioned' or block.wellFormattedContent.value == 'partiallyActioned' %}

The short syntax {{ block.wellFormattedContent }} (which internally uses the field's toString() magic method) causes problems within Twig conditionals. You can probably also get around this issue by wrapping it in curly braces.

{% if (block.wellFormattedContent) == 'toBeActioned' or (block.wellFormattedContent) == 'partiallyActioned' %}


Is there a way to override the template caching system?

"Due to the amount of queries to this backend we will probably run out of its auto incremental key space."

That would seem to suggest that maybe your template caching strategy should be re-visited?

Are there really going to be 215 million (from a signed int) unique pieces of cached content that need to be saved?

  Now my question is can I override the twig cache subsystem?

Right now, there aren't any hooks or events into the template caching layer, but a few people have asked for it to hook up to external services like memcached, redis, varnish, fastly, etc.  So it's on our list to add some events for plugins to get notified when things like cache expiration occurs for a piece of content.


Form for admins to register users from the front end

What you could try to do, though I don't know if this will work, is use the same form that craft CP uses in the backend. Using Google f12 I managed to find this:

<form id="userform" class="pane" method="post" accept-charset="UTF-8" autocomplete="off" data-saveshortcut="" data-saveshortcut-redirect="users/{id}">
<input type="hidden" name="action" value="users/saveUser">
<input type="hidden" name="redirect" value="users">
{{ getCsrfInput() }}
//Forms you want user to input
<input type="submit" class="btn submit" value="Save">
</form>

The above form is the same form that Craft uses natively to register users so it might work. Obviously, your admins will require the privileges to register users.


It's those two lines that trigger database queries

{% set url = node.url|length ? node.url : node.linkedEntry|length ? node.linkedEntry.first().url : node.customUrl %}
{% set class = node.children|length ? "has-children" %}

The first one can be optimized by using the first method in the ternary condition. You just need to know if there is a linked entry, not how many. node.linkedEntry|length queries for all matching entry models and is slower than
just calling node.linkedEntry.first(). So change it to

{% set url = node.url|length ? node.url : node.linkedEntry.first() ? node.linkedEntry.first().url : node.customUrl %}

Same applies to the node.children criteria model in the second line. Change it accordingly

{% set class = node.children.first() ? "has-children" %}

That's about all you can do to optimize the code, now you should definitly add caching to it. It's not as straightforward to implement in this situation, as there's the dynamic "active" class you want to add to the output. So you have to either cache the whole navigation for each page it's used individually (each with the active class at the right place) or you use the string replacement technique described in this SE to cache the navigation globally for all pages.


No, there's no reason why Contact Form would fail on Windows Azure specifically.

If I had to guess, I bet you've got your email settings "Protocol" configured to use PHP Mail. That particular method of handling email is notoriously unreliable, which would explain why it's working on some of your servers but not others.

I'd highly recommend switching to an SMTP service. I've personally had a very good experience with Mailgun, and I've heard others rave about SparkPost. Regardless of which service you choose, SMTP is far superior to PHP mail.

I'd also suggest reading the full Craft article on Troubleshooting Email Errors...


How can I use the entry UID in the entry URI

I think this can be a starting solution. It rewrite slug of Entry after the Entry is saved to database. The URI is constructed from it. You can try it in any plugin, only register the EVENT_AFTER_SAVE_ELEMENT in init() function of Plugin.

use craft\events\ElementEvent;
use craft\services\Elements;

Event::on(
    Elements::class,
    Elements::EVENT_AFTER_SAVE_ELEMENT,
    function (ElementEvent $event){
        //identify the right Entry for example test sectionId, typeId, authorId
        if ($event->element instanceof craft\elements\Entry) {
            $entry = $event->element;
            //only newly created
            if($event->isNew){
                $entry->slug = $entry->uid;
                Craft::$app->elements->saveElement($entry);
            }
        }
    }
);


Response via Slack from Brandon Kelly:

  Accessing custom field values from PHP is the same as in Twig - once you have the UserModel it's just $user->myCustomFieldHandle
  or $user->myEntriesField->first(), etc.

Managed to get via following: $user->company->first()->title


How do I create a plugin to create and save multiple entries from one front-end form?

I'd go with your first option.

Grab the $_POST values via craft()->request->getPost(), assemble them in your multiple EntryModels, validate each model, then pass them off to craft()->entry->saveEntry().


How do I proceed when I want to show another language when the actual language is deactivated?

So thanks to Brad I found this solution:

{# Get all entries regardless if the locale is enabled or not #}
{% set allEntries = craft.entries.section('yourSection').status(null).localeEnabled(false).find() %}

{# Set the other locale (could be done differently, but since I have only two, I chose the easy way) #}
{% if craft.locale == 'de' %}{% set otherLocale = 'fr' %}{% else %}{% set otherLocale = 'de' %}{% endif %}

{# Get all entries that are not disabled regardless if the locale is enabled or not #}
{% for entry in allEntries if entry.enabled == 1 %}

    {# if the locale is turned off, search for the entry in the other language #}
    {% if entry.status == 'disabled' and entry.localeEnabled == 0 %}

        {# Get the same entry in the other locale #}
        {% set otherEntry = craft.entries.id(entry.id).locale(otherLocale).first() %}

{{ otherEntry.title }} ({{ otherLocale|upper }})

    {% else %}

{{ entry.title }}

    {% endif %}

{# else (for the loop) all the entries are disabled #}
{% else %}

No results

{% endfor %}

It works great for my case.


I've run into this situation in various scenarios as well where a front-end entry form fails to save anything and just seems to be reloading the page. Almost always it has had to do with overlooking a required field or some other small detail, as Douglas mentions in his comment.

If all of your fields are not required, make sure you are still setting fields like the Title field, which are necessary for your Entry to save properly.

One way to help troubleshoot is to take a look at all of the errors you are getting back. If you are just trying to output errors for the fields you are submitting you may be missing seeing an error for another field that is giving you an error but that you are not outputting.

When a front-end entry form fails to submit, Craft will add any errors to the EntryModel and return it to the page. If you have devMode enabled, you can dump all of the errors from your submission with the following line of code to help troubleshoot:

<pre>{{ dump(entry.getErrors()) }}</pre>


How to block direct access to templates (hiding templates)

If your template is _example.html, you include like this:

{% include '_example.html' %}

It also works to have a template in a directory that starts with an underscore. So you could name the directory _includes, name the template in there example.html and include it like this:

{% include '_includes/example.html' %}

Either way, the template can't be accessed directly.


How Do I Select the second instance of a certain block type

You could save that second text block's ID to a variable and compare against that in your text partial:

_entry.html:

{% set textBlocksIds = entry.postBody.type('text').ids() %}
{% set secondTextBlockId = textBlocksIds|length >= 2 ? textBlocksIds[2] : textBlocksIds[1] %}

{% for block in entry.postBody %}
    {% include 'blog/blocks/_' ~ block.type ignore missing with {
        'block': block,
        'secondTextBlockId': secondTextBlockId
    } only %}
{% endfor %}

blog/blocks/_text.html:

{% if block.id == secondTextBlockId %}
    {% include 'blog/partials/_restaurants' %}
{% endif %}


Image Transform Internal Server Error (500 code) after Craft CMS update

More a workaround than a solution but I added

  'imageDriver' => 'gd'

 to the config so it didn't use Imagick anymore. Works as supposed to now.


Many sections use one template: How do I get current section?

If I understand you right, you could just use the Entry Model which is automatically populated as entry if you call the Index. Entry Model objects have a method getSection() which returns the Section Model to which the Entry Model object belongs.

https://craftcms.com/docs/templating/entrymodel#getSection

Edit:
Okay I think I didn't understand you right. I think you get the error because no section is related to your index template and instead you call it directly. You actually don't want that, so rename your index file to _index in order to prevent direct call. If you call it directly, no entry object is populated and voilà: error.

You can probably achieve what you want by utilizing the way Craft's example website Happy Lager does it:

You have your channel sections with their handles a, b, c.... Entry Template of all is let's say whatever/_entry.
For every channel section you create a section of type single, the handles like aIndex, bIndex, cIndex.... All of these single sections point to whatever/_index as Entry Template but have different URIs, e.g. a for section aIndex.

When you hit craft.dev/a now, you get your index template whatever/_index populated with entry and entry.getSection() returns a section model of aIndex. Now you can get all entries of channel section a by using

{% set channel = entry.getSection().handle | replace("Index", "") %}
{% set entries = craft.entries.section(channel) %}

It is still kind of hacky because you have to name the section handles appropriately.


Get future multi-day event entries with custom date field

I think the simplest solution would be to make the eventEndDate field required even for single day events. Then you could do something like this:

{% for event in craft.entries({
  section:'events',
  eventEndDate:'>= '~now,
  limit: 3,
  order:'startDate'
}) %}

Given you have 3 events:

Starts Monday, ends Friday.
Starts Wednesday, ends Thursday.
Starts Thursday, ends Thursday.

On Wednesday, you'll still see those events in order (1,2,3).


I don't think it's possible to do what you're trying to do in a single ElementCriteriaModel query.

These questions are basically asking the same thing and can confirm it.


Filter results by users contained in a Users Relations RelatedTo field

If I understand you correctly, you want to exclude any entry that has any user from a certain user group selected in a certain Users field.

Here's an approach that I believe would work:

{# Get the users that should be excluded #}
{% set excludedUsers = craft.users.group('groupToExclude').limit(null) %}

{# Get the entries that should be excluded #}
{% set excludedEntries = craft.entries.section('logsQA').relatedTo({
    targetElement: excludedUsers.ids(),
    field: 'logGeneral_sonographerName'
}).limit(null) %}

{# Get the entries that should be displayed #}
{% set entries = craft.entries.section('logsQA').id('and, not '~excludedEntries.ids()|join(', not ')) %}

What the above does is to first pull the users that should be excluded (you could use the groupId parameter instead of group if you want to), before using those users to pull the entries that should be excluded.

Finally, the entries that should be displayed are pulled – the key here is the use of the id parameter to specifically exclude a list of entry IDs.


FeedMe SSL error - cURL error 35: SSL connect error

Most likely the PHP curl version that's on your box is trying to connect to the endpoint using an older SSL protocol (TLS 1.0, 1.1, etc.) and the endpoint requires something higher (TLS 1.2, 1.3, etc.).

http://blog.techstacks.com/2010/03/3-common-causes-of-unknown-ssl-protocol-errors-with-curl.html

The command line version of curl is probably using a newer protocol.


Craft isn't regenerating the image transform when the focal point changes

Changing a focal point will delete all the transform files as well as transform index entries, so I suspect that you're just seeing cached data.

The reason why it works when changing quality is that that will actually affect the path where the transform is located, so the browser will actually have to look for the new file instead of assuming that the cached version is safe to use.


Twig 'starts with' not evaluating variables properly

I'm going to assume that your imageWidth field is a dropdown menu... correct me if I'm wrong. When you output a dropdown fieldtype in your templates, it's an object, not a string.

Scenario 1: Comparing objects
{% if block.imageWidth starts with block.imageWidth %}

The starts with comparison operator is designed for strings, but here it's handling two objects. Makes sense that it would just give up and evaluate to false.
Scenario 2: Comparing strings
{% if '{{ block.imageWidth }}' starts with '{{ block.imageWidth }}' %}

In Twig, you can't nest tags. Those strings are being read literally, and not parsed out into their respective values. So what you've got here is a comparison of two identical strings... Makes sense that this would evaluate to true.
Scenario 3: Comparing values
{% if block.imageWidth.value starts with block.imageWidth.value %}

Working under the assumption that imageWidth is a dropdown menu, then you are actually getting an object from block.imageWidth. Twig isn't confident that you actually want a string here, so you'll need to append .value to specifically get the value of your field.

I've seen this trip up a few people, but it makes perfect sense once you wrap your head around it. Many objects in Craft will try to automatically "stringify" themselves when output directly using curly braces. But when it's not a direct output tag, you'll generally need to tell Twig that you specifically want the string value, and not the object itself.


How to prevent cache busting (preferably on a single section)?

cacheElementQueries set to false should cause the behavior you're looking for. i.e. Craft no longer keeps track of element queries inside of the cache tag for use in when deciding when to bust them.

Might also be worth looking at the Cache Flag plugin as that lets you more explicitly define when you'd like caches to be busted.


There's no way of doing that natively.

When you're cropping an image with Craft, it zooms in as little as possible.  So, if you have an image that's 800x600 and you crop a square at 500x500, Craft won't zoom in at all.

When cropping is finished, the next task is to get the focal point as close to the center of the final image without crossing out of bounds.

Consider if Craft tried to put the focal point in the center no matter what. If the focal point was 100 pixels away from an edge and you wanted a square of 300x300, that would result in 1.5x zoom which would be a less desired outcome for many people.


Does anyone use Craft CMS to set up an intranet for client?

There currently isn't a single plugin that does everything that BuddyPress does.

There are calender plugins, commenting plugins, social login and oauth plugins and Craft Pro has built-in front-end registrations with member accounts with user groups and permissions. It would be up to you to tie all of these pieces together for your site's requirements.


When creating new assets what should we put in base Url and document root file?

You can use the aliases for that. @web and @webroot are aliases which are included in Craft by default, @web is pointing to the base website url and @webroot is pointing to the document root file path (absolute path) respectively.


You can simply create a 'robots.txt' file in your templates folder and populate it using twig (templates do not need to end in .twig). Not sure what you're trying to control exactly, but something like this should technically work.

User-agent: *
{% set entries = craft.entries.limit(null) %}
{% for entry in entries %}
    Disallow: {{ entry.uri }}
{% endfor %}

Terrible example but you get the idea. Then just delete the robots.txt file that is in your public folder.


Frontend upload for images, mp3s and video?

Yes you can do that with an Entry Form in your template.

Have a look at the assets fields article in the docs, there is a small section about uploading files from front-end forms.


I figured it out. It was super unexpected, after turning on errors finally, I got

 Fatal error: Class 'Craft\AppPathCacheDependency' not found in

Then I realized that GIT didn't include that file, still not sure why, but now I know the cause.


Load balancing nodes configuration (3 Craft nodes behind F5 Big-IP)

Update:

Am I allowed to change my mind on this? :)

My original answer didn't take into account storage/logo, storage/backups and anything else that a plugin might be storing in the craft/storage folder.

So it's probably going to be much cleaner and safer to have CRAFT_STORAGE_PATH point to the shared file system.

I would set CRAFT_STORAGE_PATH and have them write to their local file systems.  That way you have independent logs for each web server.
With that set to 'true', the PHP session files will go to whether PHP/nginx are configured to send them.
The cacheMethod config setting it purely for data caching. It's set to 'file' by default which will write to craft/storage/runtime/cache, but you can change that to some other caching method.

Actually, if you do #1, then 2 and 3 would resolve themselves, no? You'd want to make sure that your load balancer has stick sessions enabled so that a user would get sent to the same web server for subsequent requests.


There was a typo hidden in there, otherwise the logic works. To get children as anchors in a structure, the following should do the trick:

{parent.uri}{% if object.getDescendants().total() != 0 %}/{% else %}#{% endif %}{slug}


To simply pass the variables to your plugin or module use:

MyPlugin::getInstance()->checkCommerceRecord($user, $dateTime);

To pass to a service (see the Creating a Service section of the docs) use:

MyPlugin::getInstance()->myService->checkCommerceRecord($user, $dateTime);

To pass it with your model use:

$model = new WFWPluginModel(['setUser' => [$userId, $dateTime]]);

MyPlugin::getInstance()->myService->checkCommerceRecord($model);


Contact Form plugin - Error loading 404 Pages

Anywhere you've currently got something that looks like this:

{% if message is defined %}{{ errorList(message.getErrors('fromEmail')) }}{% endif %}

Try changing that to:

{{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

And you'll want to do that for the other attributes, too ('fromName', etc.).


How can I use a WHERE statement in my template?

You would first need to query for the users that match your criteria and than query for the profile entries which are related to one of these users.

{% set userIds = craft.users({
    year: craft.request.getSegment(3),
    userOptions: craft.request.getSegment(2),
}).ids() %}

{% set profiles = craft.entries({
    section: 'profiles',
    relatedTo: {
        targetElement: userIds,
        field: 'userAccount',
    },
    with: ['userAccount'],
}) %}


Force Field Limitation in Drafts - Front End Form

Custom field validation won't run for disabled entries or for drafts, regardless of whether it's a front-end request or a CP request.

There is an Always Validate plugin that changes that behavior for disabled entries/categories.  It could pretty easily be modified to do that for drafts as well.


Translating a section's title field on save

Figured out something that works, though I can't explain why:

{{ object.section.name|t(language=object.locale) }}

Update

Here's how to do it for Craft 3:

{{ object.section.name|t('site', language=object.site.language) }}


On a default Craft install if I'm logged out and hit the front-end of the site with purposefully messed up database credentials, I get a nicely styled Craft 404 page if there is no craft/templates/404.html and a front-end 404 page if there is.

I believe the issue is that you've got your own front-end 404 template that's also trying to access the database and it can't.

So basically the first error is thrown (can't access the database), then another error happens (I really can't access the database) when trying to tell you about the first error.

By this point, Yii thinks the error has already been handled, so it falls back to CApplication->displayException().  I assume in this case, some content header or encoding isn't set properly and you see the garbled ’ character.

So until/if we can think of a way to guard against this scenario, your best bet is to make sure that your 404 template isn't triggering a database call.


Craft Commerce: Add to Cart and then Redirect to Product Page?

You would need to use javascript to change the redirect input's value

<input type="hidden" name="redirect" value="commerce/cart">

For example on the 'add and create new item' button you could do something like this using jQuery:

   $('.addAndCreateNewBtn').click(function(e){
       e.preventDefault();
       var $form = $(this).closest('form');
       $form.find("input[name='redirect']").val('anotherUrl');
       $form.submit();
   });

The above is untested, but should replace the redirect value then submit the form.


Subdomain database configuration picking up root domain config

As long as you have the more specific one at the top of your array like you do, it should work.

It looks like your using some custom (non-stock) Craft config logic judging from the $customDbConfig variable.

What happens if you echo $_SERVER['SERVER_NAME']; from the test1.foo.com domain?

If it's an exact match and it is still not selecting the right database, then I'd suspect your custom logic.

Strip all of that out to just Craft's default multi-environment config and see if it works that way.


How to save a matrix content of a new entry in my plugin?

Ok there are two parts to this question - how to save relationships and how to save matrix blocks whilst saving an entry.

How to save relationships

To deal with the first, it is my understanding that the entries need to exist first so you may need to create them if they aren't already. Then all you need to do is pass an array of entry ids to the relevant field:

$entry->getContent()->entriesField = $targetEntryIds;

How to save matrix blocks whilst saving an entry

Bryan is correct in that you can create and save blocks all by themselves, however if all you want to do is add some blocks to a new entry then the following setup will work just fine:

$matrixData = array();

$matrixData['new1'] = array(
  'type' => 'blockType',
  'enabled' => true,
  'fields' => array(
    'fieldOne' => 'Some string or data',
    'fieldTwo' => '12'
  )
);

// You can repeat this part for each block you want to add, just increment the newN number.
$matrixData['new2'] = array(
  'type' => 'blockType',
  'enabled' => true,
  'fields' => array(
    'fieldOne' => 'Some more text',
    'fieldTwo' => '16'
  )
);

// set matrix field to contain those blocks before saving the entry
$entry->setContentFromPost(array('matrixField' => $matrixData));

This gist from Brandon explains all on the Matrix front, I am merely repeating most of it here for your benefit.

Best of luck!


Limit the entries element API will return based on the post date

Within the criteria for the endpoint, set

'postDate' => '>=' . date('Y-m-d', strtotime("-90 days"))

Of course you can adjust the date to suit your needs.


By default browsers look for a favicon at the root of your web directory. So if you do not add a link in your head section, but you have a favicon.ico at webroot, you will still see it.

However, a favicon can technically be located anywhere. If you have a multi-site installation you can reference it like this (note that you should always use a fully qualified URL or you may run into issues with IE):

<link rel="shortcut icon" href="https://yourbucket.s3.amazonaws.com/{{currentSite.handle}}/favicons/favicon.ico" type="image/x-icon">

Insert Craft's current site handle tag so that you can use the same code on all sites. Then you'll just need to create a paths in your S3 bucket to match.

Regarding multiple sizes, you should include more than just a 16x16 favicon. This is what I have which is all related to icon display:

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#888888">
<meta name="msapplication-TileColor" content="#ffc40d">
<meta name="theme-color" content="#ffffff">

The manifest, mask-icon, msapplication-TileColor, and theme-color all refer to how your favicon will appear on platforms including Safari, Windows and Android devices.

You could add an image transform to your asset volume which creates each of the required sizes, or you could direct your client to upload multiple sizes. It may be easier to send them to this site to generate favicons which they can then upload to their assets volume.

Disclaimer, I have no affiliation to the Favicon Generator site -- I just use it frequently. I generated the code you see above using this tool. If you're looking for a reliable way to generate your favicon size variations and the associated code, this online tool does the trick.


Display different Categories groups in custom breadcrumbs

I've managed to solve it. {{ category.counties.first().title }} did the trick.

Clearly I just needed to print the category field, although I'm not sure why it needs the .first() after category.counties to print it? But it works at least after days of struggling to find an answer.


An SEO software tool says 'keywords' meta tag is obsolete

So this isn't a simple answer, because we don't know how the SEO has been implemented on your particular site. It could have been done manually, or they could have used my SEOmatic plugin or it could have been another plugin. You also don't mention what version of Craft CMS you're using.

In any event, what that SEO tool is telling you is that the <meta name="keywords"> tag is largely ignored by Google. I say largely, because if you stuff it with all sorts of keywords that look "spamy" it can be a negative ranking signal for your site.

Other search engines such as Bing, Yandex, etc. do look at the meta keywords tag, though, and as long as you're not "keyword stuffing", there's no harm in leaving that tag in there.


Doesn't handle exporting data, but FeedMe can handle importing XML or JSON content for most element types.


Include an extension in your template name, including ".twig" (e.g. robots.txt.twig)

This is because right now, if your template path includes an extension, Craft assumes that you’re explicitly providing the full template path, and won’t try appending the defaultTemplateExtensions to it. (See a full explanation here.)

robots.txt does make a good use case for why we should append those extensions anyway, though. We shall consider it :)

UPDATE

We changed this behavior in Craft 2.2, so now a request to /robots.txt could resolve to a template called /robots.txt.twig. http://buildwithcraft.com/updates#build2579


Craft 3: Upload user photo from front end

The field name used for the user photo has changed to photo, so the bare minimum change to make this work is modifying
<input type="file" id="userPhoto" name="userPhoto" value="Upload">
to be
<input type="file" id="userPhoto" name="photo" value="Upload">

You'll probably want to use transforms, when outputting that image, too.

Also, I'd stick with currentUser.photo or currentUser.getPhoto(), instead of using a hybrid currentPhoto.getPhoto, but that might just be me.


I try to add element to structure, and I want to add to this element parent ID

The fields array may only contain names that represents handles in your fieldLayout but the parent attribute is a property of your object rather than a field - you can set it via parentId. You may want to inspect your CP form in order to see how you need to define attributes

    Date
    <select name="parentId">
        {% for entry in craft.entries.section('order').level(1).find() %}
            <option value="{{ entry.id }}">{{ entry.title }}</option>
        {% endfor %}
    </select>


A user deleted my craft Admin account, what to do?

You need to check if the normal user has an administrate permission, you can check at user -> permission. Even a normal user you still can give it an administrate user permission without change it into a admin user, but this permission is off by default for normal user.


Routing: How can I ignore a parameter in route definition?

It sounds like you might be trying to blend Craft/Yii routing with Rewrites (if you're coming from an Apache background).

I believe what Craft interprets this as is an attempt to map a request to locations/or/my-entry-slug to the <slug> (literal) action of the locations controller (which doesn't exist).

If you just want to render a template for these entries, you can set up your route like this:

'locations/<state:[a-z]{2}>/<slug:{slug}>' => ['template' => 'locations/entry']

This way, you'll get a state and slug variable in the templates/locations/entry.twig template, with which you can look up the Locations Entry you want.

To troubleshoot further, we might need a bit more information about how your Locations Section is set up, and the goals for the route!

  If you're just looking to capture and redirect legacy URLs, be sure and check out the Retour plugin.

  Additionally (and for anyone who finds this in the future), I'd recommend reviewing the advanced routing docs.


Select Transform Feature with Asset Field

Asset fields require a transform to be set manually in the template or can be Created in the dashboard and the transform name used in the template.

{% set thumb = {
    mode: 'crop',
    width: 100,
    height: 100,
    quality: 75,
    position: 'top-center'
} %}

<img src="{{ asset.getUrl(thumb) }}">


Logistics of loose field naming and re-use with Relabel

Relabel is a great plugin and the option to re-use fields without sacrificing semantics for the content editor can be very useful, especially if you (potentially) face creating a lot of similar fields (hundreds) in order to provide specific labels and instructions. I'm not aware of any technical or performance related issues with the plugin, but here's a couple of things worth considering before going all in:

Your content model will be less flexible. For instance, if you use the same Rich Text field everywhere, you're not going to be able to have different settings for different types of content (perhaps entry type X needs a different Redactor config than entry type Y, or you need to disable/enable HTML purification for a specific piece of content – there's no way to make that happen if you use the same field for everything). This is especially troublesome if you only figure out you need different settings for different types of content late in development (or even after initial development has concluded), i.e. after adding a ton of content to the site. Of course, this applies to Craft even if you're not using Relabel, but personally I always lean towards creating two fields if there's even a slight chance I'm going to need different settings for different things.
Your templates will be less semantic. Even if you add the labels "Hero text", "Body" and "Description" to a Rich Text field with the handle richText across your content in the CP, you'll still have to call {{ entry.richText }} everywhere in your templates. Losing the semantics and clarity of entry.heroText, entry.body and entry.description could make your code more confusing and harder to debug and/or read in the long run.


Feed Me with Related Entries Fields - One to Many Relationship

Why not define the attendees as an array in your JSON? This should allow multiples to be added to your field.
[
    {
        "Meeting Title" : "Project Kickoff"
        "Meeting Attendees" : ["John Doe", "Jane Smith", "Jim Brown"]
    }
]


Pass a nested array to the params argument inside Craft's url() function

Yeah, looks like Craft's url() method doesn't support nested array syntax for querystring params.

If you still want to use it, then you'd need to flatten it with unique keys such as:

Array
(
    [q] =>
    [cat] =>
    [city0] => 28
    [city1] => 26
    [sort] => asc
    [order] => name
)

Alternatively you can manually build the URL yourself in Twig in whatever format you'd like.


How do I send an email to multiple recipients?

You can loop through a list of your recipients:

// Comma-separated list of recipients
$recipients = 'person1@example.com, person2@example.com';

// Break out recipients into an array
$recipientList = explode( ",", $recipients );

// Create the globally known things about the EmailModel
$email = new EmailModel();
$email->subject = 'My Email Subject';
$email->body    = 'My Email Body';

// Loop through each recipient in the recipient list
foreach ( $recipientList as $recipient )
{
    try
    {
        // Add a specific recipient to the email model
        $email->toEmail = $recipient;

        // Send the email
        craft()->email->sendEmail( $email );
    }
    catch ( \Exception $e )
    {
        // Do nothing
        return false;
    }
}


You can leave the with lightswitchTest part off altogether, and all the variables from the parent template will be available inside the include too.

with expects an array, where the keys correspond to the variable names and their values, so if you did want to explicitly pass that in (say as a different variable) you could use:

page.twig

{% include "_snippets/thingy" with { active: lightswitchTest } %}

thingy.twig

<div class="panel{% if not active %} notActive{% endif %}">
    {# bla bla #}
</div>


What does {{ hiddenInput('enabled', '1') }} in an entry form do?

It is to generate an HTML input tag with type of hidden.
This will not appear on the screen like a normal input does.
For more information related to input type hidden, you can refer to this.

enabled means that the entry will be saved with its status toggle set to the “enabled” (green) position.