Lingering artifacts of deleted Sprout Forms plugin causing queue failure for updating search indexes

UPDATE: This should no longer be an issue. All of our plugins have been reviewed and updated with more consistent uninstall behavior.

If you no longer have those plugins installed, you should be able to drop all of those tables without creating any new issues.

That may not clean up all of your data though, as the queue error is pointing to an orphaned Element. To see any orphaned elements you can run a query search for all Sprout elements on your elements table. The following may need to be adjusted if you have a different database prefix:

SELECT *
FROM craft_elements
WHERE type LIKE '%barrelstrength%';

Deleting these Elements from your elements table should cascade and clean them up anywhere else they may be used in the database. Be careful with the following operations and be sure to test on a dev database to make sure everything works as you expect. There could be scenarios I'm not considering.

Once you find the Elements you want to delete update your query to just grab the Element IDs of the specific Elements you want. You could also query these ID values from the plugin-specific element tables if they are still in your database.

SELECT id
FROM craft_elements
WHERE type LIKE '%barrelstrength%'

To delete Elements you're going to pass those IDs to a delete statement. A standalone delete query will look something like this:

DELETE FROM craft_elements
WHERE id IN (1, 2, 3);

If you want to combine both queries since you're selecting the IDs from the same table that you are deleting from you can create a temp table to get around that. This can result in a slow query if you have a large number of elements. In that case, you could delete multiple batches of a smaller number of elements.

DELETE FROM craft_elements
WHERE id IN (
    SELECT tempElements.id
    FROM (
        SELECT id
        FROM craft_elements
        WHERE type LIKE '%barrelstrength%'
    ) tempElements
);

Again, please be careful when operating on the Craft database directly. Be sure to create backups, test on a development database, and review things closely. Craft has a highly relational data structure and plugins may behave in different ways in how they store their own data.

A less risky way of approaching this may be to write a short script and delete the Elements using the Element API:

foreach ($elementIdsToDelete as $elementId) {
  Craft::$app->elements->deleteElementById($elementId);
}


Comparison with an integer from a dropdown list not working

You'll want to use:

{% set mylevel = currentUser.level.value %}

If you just use currentUser.level and assign it to a variable, then what you'll get back is a MultiOptionsFieldData class, instead of the value you are expecting.

There is a note on the bottom of the page here that describes it.


Of course, just create a new asset source (settings > volumes > new volume)
then in your image field select 'Restrict uploads to a single folder' in your field and then select the asset source you just created.


Not manually but you can search for the field in your database. If the plugin uses the normal craft_fields you can copy it's settings and paste it in a new record


Is there a template conditional to determine whether a plugin is installed?

This should do it:

{% if craft.cornballer is defined %}
    Never fear... CornBaller is here.
{% else %}
    I'm missing my CornBaller.
{% endif %}


It looks like your loops are causing Yii to add joins to the craft_relations table once for each iteration of your loop.

{% for id in locId %}
  {% set relatedTo = relatedTo|merge([id]) %}
{% endfor %}

{% for id in typeId %}
  {% set relatedTo = relatedTo|merge([id]) %}
{% endfor %}

I would guess that either locId or typeId contains an array with many values. Try using {{ dump() }} or {{ locId | length }} to see how many values you are dealing with.

You might need to refine the query for each of these locId and typeId to ensure you get a single result.

Alternatively if you really want to search among that many records you might need to redesign your approach. Perhaps build an SQL query that achieves what you want first then work your way back from there.


What does cart.currency return?

The Twig currency filter ultimately uses Yii's CNumberFormatter class. This uses the symbol you are seeing as a default placeholder for the currency symbol if one cannot be determined from the value of the $currency parameter passed to it. This would indicate that the value of cart.currency is not as expected. You'll need to make sure that the cart variable is being set correctly in your template, then this should work.


The {% cache %} tag will detect if there are any ungenerated image transforms within it. If there are, it will hold off on caching the template until the next request, so that the temporary image URL won’t get cached.


I haven't found how to do it through the UI but it's possible to add the section names in translation files as keys and then translate them in the views using {{ "key_name" | translate }}.

You must follow this example but keeping in mind the translations folder changed its location and structure from Craft 2 to Craft 3.

You have to place it right under your project directory:

yourProject
|--templates
|--translations/
|---en/
|-----site.php
|---es/
|-----site.php
|--vendor


How does a plugin make use of Craft's storage?

craft/storage/ is used for all sorts of things, so there’s no single API for storing things in there. Mostly you would just be working with PHP’s standard IO functions like file_put_contents(). There are some handy functions in Craft’s IOHelper class too.

You can get the path to the storage folder via PathService::getStoragePath():

$storagePath = craft()->path->getStoragePath();

IOHelper::ensureFolderExists() is a handy function for creating a subfolder for your plugin within craft/storage:

$myStoragePath = $storagePath.'myplugin/';
IOHelper::ensureFolderExists($myStoragePath);


How do you use 'if' to stop an empty Matrix block from displaying?

If a Matrix field / block is empty it won't output at all but you can try checking the length in an if statement like:

{% if entry.modelDataType1 | length %}
    // matrix content here
{% endif %}


Sort matrix blocks in admin by a field within the matrix?

There is nothing that will automatically sort blocks for you in the Control Panel. Without writing a plugin with some very fancy JavaScript, the only way to arrange blocks is manually.

You can manually arrange your blocks by clicking & dragging the crosshairs in the upper-right corner of each block:


Recommended Structure - One Site with Pages With Totally Different Layouts?

Option 1 is a safe bet. This allows you to have completely separate, editable templates for each chosen year. You can then change the page slug to match the year of that page. You can reuse fields year over year if you'd like or create new fields for each year. Plugins like seomatic will help you create individual SEO content on a per template basis.


How do you use the Venti Calendar plugin with the Element API plugin?

I don't have the Venti Calendar plugin, so I can't test this, but it should be as simple as setting the elementType propety to whatever custom element type the plugin has created and you want to use and (optionally) setting any criteria you want defined by the element type.

return [
    'endpoints' => [
        'news.json' => [
            'elementType' => 'Venti_Event',
            'criteria' => ['key' => 'value'],
            'transformer' => function(Venti_EventModel $eventModel) {
                return [
                    'key' => $eventModel->property,
                ];
            },
        },
    ]
];


Craft CMS plugin route redirects to login when not logged into Craft

You need to explicitly allow allow anonymous access to your controller's action.

More info on how to do that here: http://buildwithcraft.com/docs/plugins/controllers#allowing-anonymous-access-to-actions


How to saveElement in EVENT_AFTER_SAVE_ELEMENT without infinite loop

I got this working by using the EVENT_BEFORE_SAVE_ELEMENT and adding the asset to the entry asset field 'pdfThumbnailImage' by using the setFieldValue.

 $entry->setFieldValue('pdfThumbnailImage', [$assetId]);

You dont need to save the element - leave this out

 Craft::$app->elements->saveElement($element); // causes loop


Structure listing order & classes based on lightswitch value

Whilst I can’t offer the exact template code for an answer right now as I am in bed (have I broke the stack rules?) it might be worth checking out the |batch filter.

Or taking elements of this answer and making it suit your requirements Making an entry grid with Batch 2,3 (2 in row then 3 in row)

And reading this https://twig.symfony.com/doc/2.x/filters/batch.html


Compose URL POST parameters to filter entries by category?

I'd split the parameter string into an array and then loop through the categories and use a conditional to check if the value already exists in the parameter. It's not so easy to describe in detail, that's why I added lots of comments to the code (untested!).

To work in your other parameters (size, etc.), simply add them to your links exactly how craft.request.getParam() returns them. Conditionally skip the output completely if the param is empty.

{# Get the parameter (e.g. 'red,blue,black') #}
{% set currentParam = craft.request.getParam('color') %}

{# Split the parameter string #}
{% set arrCurrentParam = currentParam|split(',') %}

{# Loop through categories to output the links #}
{% for catOut in categories %}

    {# Define newParam var before loop #}
    {% set newParam = '' %}

    {# Loop through categories to compose the new parameter #}
    {% for catComp in categories %}

        {# Check if changes could happen in this loop #}
        {% if catOut.slug == catComp.slug %}

            {# Add category if it was currently NOT selected #}
            {% if catComp.slug not in arrCurrentParam %}
                {% set newParam = newParam ~ ',' ~ catComp.slug %}
            {% endif %}

        {% else %}

            {# Add category if it was already selected #}
            {% if catComp.slug in arrCurrentParam %}
                {% set newParam = newParam ~ ',' ~ catComp.slug %}
            {% endif %}

        {% endif %}

    {% endfor %}

    {# Remove leading comma #}
    {% set newParam = newParam|slice(1) %}

    {# Conditionally add param to link output #}
    {{ category.slug }}

{% endfor %}


Issues loading files from within css files

For static assets I usually use something like this:

{% if craft.debugMode %}
    {% set assetsUrl = siteUrl %}
{% else %}
    {% set assetsUrl = "assets.mysite.com" %}
{% endif %}

And then I can set assets URL's the same way as navigation URLs. ie.

{% includeJsFile assetsUrl ~ "js/init.js" %}

{% includecss %}
body.landing #page-wrapper {
    background-image: url(" {{ assetsUrl }}img/pic01.jpg  }}");

}
{% endincludecss %}


Craft login redirecting to /web instead of /templates?

I found it, needed to change the SiteURL in .env file.


Set Search to query multiple attributes (e.g. title, body)

It doesn't look like it's possible to pass an array of attributes to the attribute parameter, the Craft docs explicitly state that it expects a string.

https://craftcms.com/docs/config-settings#defaultSearchTermOptions


How to exclude certain fields from .search()

Starting with Craft 3.1 the solution is easy. In the field definition there is a new checkbox: "Use this field's value as search keywords". Uncheck and you're done!

Please note that there was a bug until Craft 3.1.9.1 which prevented this from working. Thanks to Romain poirier and Brandon Kelly (https://github.com/craftcms/cms/issues/3837).


Using htaccess/htpasswd in each folder does work, but I don't find it really elegant.  Would there be a better way of doing this without Craft's users?


How to set dynamic criteria for endpoint with the Element API plugin?

Finally figured this out.
By using the variable slug in the endpoint URL I was able to listen for the category in the currently viewed category slug and pull the data i needed for my google map. The trick is to typomake the end point a function - i was trying to set the criteria outside of the endpoint which is, in retrospect, silly.

'locations/<slug:{slug}>.json' => function($slug) {

                        $criteria = craft()->elements->getCriteria(ElementType::Category);
                        $criteria->slug = $slug;
                        $category = $criteria->first();
                        return [
                            'elementType' => 'Entry',
                            'criteria' => [
                                'section' => 'directory',
                                'relatedTo' => ['targetElement' => $category],
                                'limit' => null,
                            ],
                            'transformer' => function(EntryModel $entry) {
                                return [
                                    'title' => $entry->title,
                                    'mapinfo' => $entry->mapaddress,
                                    'url' => $entry->slug
                                ];
                            },
                        ];
                    },


As with most questions and problems with Redactor, the answer to this should probably be: don't do it in Redactor.

You could just add a new block type to your Matrix field that does just one thing: add the div tag (or close it, if there's an open one). Another possibility is to do this all programatically, check if it is the first or the last block of a specific type and conditionally add the markup to wrap them in your div.

Have a look at the discussion here, to read more about these solutions:
Solution for Matrix-within-Matrix (or More Robust Table Fields)

And if that's still not flexible enough, you could also have a Super Table within you Matrix (within a Super Table, within...).


Plugin: Linking elementSelectField to own plugin models

Perhaps I am misunderstanding what you are trying to accomplish, but it seems like you should be able to accomplish what you are looking for with Craft's native EntriesfieldType.
Regardless, I'll write up a few options for creation your own Entry select modal as well as a custom FieldType.

If you check out Craft's BaseElementFieldType which all of Craft's Element Field Types extend, you'll see that it has an attribute called $inputTemplate with the value '_includes/forms/elementSelect'. This is the template that is rendered for element fields on the entry edit pages, and is accessible from the forms macro!
To create an element select modal from within a template, you can call

{{ forms.elementSelect({options}) }}

Don't forget to import the forms via {% import "_includes/forms" as forms %}

If you check out the elementSelect template, you can see all of the fields that are required to create an element select modal. This is really handy and it becomes really easy to create an element select modal. Inspecting an element field type's getInputTemplateVariables() will show you what variables are passed. Use of a debugger here and setting breakpoints to walk through the flow of execution helps a lot as well.

If you check out the EntriesFieldType, you'll see that it relies almost entirely on the logic in the BaseElementFieldType, and just updates the $elementType property, and overrides the getAddButtonLabel() method. So the input template variables defined in the base class are the ones that are used.

Now if you are defining a custom field type, you have this handy tool to create a modal. You can create an input template and make this call, and then implement getInputHtml() to pass the necessary variables and render the template.

Note: If you have never done this before, check out Craft's documentation on how to create your own custom field.

Let's say you want to create a custom field type that is similar to the Entries field type but you want it to have some additional functionality outside of what you get with the EntriesFieldType. No problem! Craft has made it really easy to do this. What you can do is create a field type like you would a normally, (follow the same naming conventions - PluginName_NameFieldType.php within a fieldtypes directory in your plugin), but instead of extending BaseFieldType, you can extend EntriesFieldType and get all of the functionality of the EntriesFieldType for free! Then you can override methods as you see fit in order to create your custom functionality.

For instance, lets say you want your entries select field to only be able to select fields from your Companies channel, you could override the inputSelectionCritieria() method and return

$criteria['id'] = $ids

Where $ids is an array of element ids.

Note: Criteria returned by this method and passed to elementSelect is not a CriteriaModel, but is an array with some pretty specific keys. For some more detailed documentation, check this out, and also check out the BaseElementFieldType implementation.

Extending the EntriesFieldType is really handy because you can rely on Craft for most of the logic. For instance, if you want your Entry select modal to be exactly the same as the default one, then you don't have to define your own input template. You can modify the input variables as you see fit by overriding methods and adding your own custom functionality, and then let the BaseElementFieldType render the modal itself.

This post has been focused on backend stuff for modals and field types, but it is also possible to extend the modal js for a more custom experience. Check out this stack post and Peter Tell's Many to Many plugin for a complete example.

The best tool to figuring out what is going on is inspecting the Craft core as well as other plugins. There isn't great documentation on how to do a lot of this stuff, so if you have more specific questions, please feel free to leave them here! I'd love to expand this answer to have more detailed explanations. Hopefully this can help get you started!


I've tested this locally on Craft3 and Craft2 and it seems that the username field is not case sensitive (e.g. admin, ADMIN, and AdMiN all worked equally as well for me).


Does Craft Commerce support Worldpay refunds?

The answer looks to be "Not if you're using the Legacy gateway" that all my clients seem to be using.


Import Stripe subscriptions into Commerce 3

Craft are hoping to release this as an update to Commerce in the next month or so!


Re-using path segments for an additional domain?

In Craft, there is no such thing as a "section path" – there's only the "Entry Template" path (which tells Craft which template to load when the URL for an Entry in that particular section is requested) and the "URL format", which tells Craft how it should construct the URLs for the entries within that section.

It's actually totally possible to have multiple sections use the same URL format – e.g. blog/{slug} – so that part is easy; just use the same format for both of your blog sections, and all your URLs will be consistent out of the box (the only drawback to be aware of is that if you create entries with identical names within both sections, Craft will suffix the auto-generated slug for the newer entry with a number, i.e. my-generic-blog-post-title-2).

I'm assuming your blogs should use different templates for both their index and entry pages, so with the above URL format in place, it's simply a matter of routing the requests to the correct template(s).

The entry template is easy. You can set different paths for the two blog section's Entry Template path settings, e.g. blog/blogA/_entry and blog/blogB/_entry, or you can use the same path, e.g. blog/_entry for both. If you use the same template, you can conditionally {% include %} a blog specific template by testing the entry.section.handle value, e.g.

{% switch entry.section.handle %}
    {% case 'blogA' %}
        {% include 'blog/blogA/_entry' %}
    {% case 'blogB' %}
        {% include 'blog/blogB/_entry' %}
{% endswitch %}

For the blog indexes – i.e. domain.com/blog and domain-two.com/blog – it's important to realize that in Craft, there is no inherent relationship between templates and sections. For instance, even if you have a section with the handle blog and a template templates/blog/index, Craft won't automatically "connect" the template and the section, in terms of, for instance, populating the template with entries or other data related to the blog section.

What Craft will do, is to route all templates (that aren't hidden using an underscore prefix, i.e. _secret.html) to URLs. This means that if you do have a template under templates/blog/index.html or templates/blog.html, Craft will load that template whenever the URL domain.com/blog (and domain-two.com/blog) is requested.

In your case, you can exploit this behaviour by creating a template called templates/blog/index.html. Inside that template, you can add a {% switch %} statement similar to the one in the entry template, but this time looking at the craft.request.serverName variable (I'm assuming you've created index templates for each of your blog sections under templates/blog/(sectionHandle)/index.html):

{% switch craft.request.servername %}
   {% case 'domain.com' %}
       {% include 'blog/blogA/index' %}
   {% case 'domain-two.com' %}
       {% include 'blog/blogB/index' %}
{% endswitch %}

If you're looking for a more robust solution, you should look at Craft's multi-environment features, or possibly make use of the appId config setting; i.e. use different appId values for the two domains, and load templates conditionally based on craft.config.appId instead of hard coding the hostnames in your templates. To have Craft set a different appId based on the different domain names, you could add something like this to your craft/config/general.php file:

return array(
    'domain.com' => array(
        'appId' => 'siteA',
    ),
    'domain-two.com' => array(
        'appId' => 'siteB',
    ),
);


Using an Entry's Added Form in a template in Sprout Forms

To dynamically display a Form that you've related to an Entry using a Sprout Forms Form relations field you can pass the handle of the form to the displayForm() tag in your template:

_entry.html

{% set formHandle = entry.formFieldHandle.first().handle %}

{{ craft.sproutForms.displayForm( formHandle ) }}

There is a doc page that describes this here: Relations Field on Entry Page and depending on where you want to redirect the user after they submit the form, Sprout Forms also supports relative redirects.


New Answer based on our discussion:

<!-- Step 1. get the category you want to exclude
     since I still don't know your structure I'll just grab it
     per id. You can see that in your cp edit url (the last number) -->
{% set category = craft.categories.id(108).first() %}

<!-- Step 2. get all entryIds related to that category -->
<!-- this should be an array of ids you can dump it to check them -->
{% set entriesInCategory = craft.entries.relatedTo(category).ids() %}

<!-- Step 3 exclude those ids from your last query -->
{% set entries = craft.entries.section('blogItem').id('and, not ' ~ entriesInCategory|join(', not ')) %}

<!-- just for debugging and testing if these are the correct one -->
{% for entry in entries %}
    {{ entry.title }}<br>
{% endfor %}
<!-- then you can use your paginate with those entries -->

old Post

You can grab all entries that are related to category F and exclude them in your query

{% set catF = craft.categories.group('categories').ids() %}
{% set entriesForCatF = craft.entries({
    relatedTo: catF,
}).ids() %}

{% set entriesNotInCategoryF = craft.entries.section('blogItem').id('and, not ' ~ entriesForCatF |join(', not ')).ids() %}

{% paginate craft.entries.section('blogItem').limit(globalSettings.postsPerPage).id('and, not ' ~ entriesNotInCategoryF |join(', not ')) as pageActive, pageEntrys %}


Why is Craft hanging every time I try to save an entry?

The problem appears to be Intego anti-virus software on my one machine.  The problem does not appear on computers that lack Intego.


I'd caution against trying to adapt the ElementAPI plugin for this purpose, as it was designed to be read-only—it's basically a wrapper around Craft's ElementQuery interface, which does not handle write operations.

In lieu of that, you might take a look at the CraftQL plugin, by Mark Huot. It supports sophisticated queries (reading), as well as mutations (writing).

Otherwise, if the scope of the content you need to update is relatively narrow (i.e. you know what section and fields you need to use), I'd recommend reading through the plugin docs, and determining whether it's something you could build on your own, with a simple Controller and supporting Service(s)!


You want to use the default blank user SVG from the Control Panel on the front-end of the site when there is no photo selected?

If so, it's probably easiest just to copy it from vendor/craftcms/cms/web/assets/cp/dist/images/user.svg to a place in your public HTML folder and reference it there.

Something like:

{% if entry.author.getPhoto() %}
    {{ entry.author.getPhoto().url }}
{% else %}
    {{ url('path/to/user.svg') }}
{% endif %}


For the record, the issue, as determined from the comments above was that the Asset field settings did not allow the type of file that was being uploaded.

Updating the Asset field settings to allow the uploaded file type solved the issue.


'onBeforePerformAction' alternative for craft 2.4.0?

No, there isn't. That's why onBeforePerformAction was introduced in 2.5.

I would highly recommend that you update Craft to the latest version (2.6.2944). In addition to all of the cool features that you are missing out on, there was also a critical security update released in 2.6.2791. Without that update, you may be leaving sensitive data exposed.


What might cause logins to work locally yet not in deployed environment?

Crikey...

/admin/actions/users/login 404

https://twitter.com/nystudio107/status/895726366477344772

Forge!


Get Entries From Any Section Matching a URL segment

To check if the word jobs is in the sectionUrl you can use twig's matches to create a regular expression that looks for jobs

{% set allSections = craft.sections.getAllSections() %}
{% for section in allSections %}
    {% set sectionURL = section.getUrlFormat()|split('/')[0] %}

    {% if sectionURL matches "/jobs/" %}
        {{ section.name }}
    {% endif %}

{% endfor %}


Instead of looping through currentMemberTest, you're currently setting up a fresh criteria model in your for loop.

Use your nicely set currentMemberTest criteria!

{% for entry in currentMemberTest %}
    ...
{% endfor %}


Trouble with buildElementQuery customization

I finally found that my problem was a SQL one not a CMS one. The where conditions grouping were the source of the problem.

Here is the final code I used.

https://gist.github.com/nicolasbinet/7e3835b13c3e9c21d2fa754243242b41


How Can I Include a Conditional for First Type of Matrix

You could first set a variable to test against and then change it the first time the block type appears.

{% set firstTime = true %}

{% for block in entry.matrixField %}

    {% if block.type == "text" and firstTime == true %}

        ...Do something once...

        {% set firstTime = false %}

    {% endif %}

{% endfor %}


Probably the most Craft-y way would be to use categories for classification and set your categories to have URLs.

Alternatively, you could do this with a route that points shop/* (ie. shop/{some token} - at a template, say shop/product_type and in that template use the second segment of the url in retrieving products of the appropriate type (or, of course, create 3 routes and 3 templates if they way you're handling those index pages differs a lot).

In general how Craft deals with routes/urls is documented here:
https://craftcms.com/docs/routing
And some more info on routes is here:
https://straightupcraft.com/events/routes-and-patterns

Then to create your menu/list or whatever, something like:

{% for productType in craft.commerce.productTypes %}
  <a href="/shop/{{ productType.handle }}"{{ productType.name }}

{% endfor %}

(on phone so excuse any syntax errors)


List most recent items combined from Channel and Structure sections

I was presuming that the default Order for Channels and Structure was postDate desc. But it turns out the default for Structure is sortOrder

{% set homepageEntries = craft.entries({
    section: ['channelOne','StructureOne',channelTwo','StructureTwo'],
    order: 'postDate desc',
    limit: 15
}) %}

Explicitly stating the order seems to fix this issue


Getting ancestors for manually set parent in template

As @Robin Schambach said, you need to loop through the ancestors.

{% set parent = craft.entries.section('pages').slug('phone-directory') %}
{% for ancestor in parent.getAncestors() %}
    {{ ancestor.title }}
{% endfor %}

This won't output the Phone Directory entry since you're just looping through its ancestors. So to complete the breadcrumbs you'll need to add
{{ parent.title }} after the loop.


How to store S3 credentials in environment variables?

Not really.

In Craft 2 S3 settings ultimately get stored in the database.

Normally the answer would be "you can write a plugin that adds its own Asset Source Type and changes that behavior", but in Craft 2, it is not easy to add custom Asset Source Types, either.

Craft 3 has solved both of those problems.  You can register custom Asset Volume Types as well as override Volume settings.


The way craft()->request->sendFile works, is that it responds to the HTTP(S) request by sending your file of choice to the browsers. As you can only return one answer to an HTTP request, you'd have to first redirect people to a confirmation page. On that page, you could have a download button, and use some Javascript to force the download to take place on page load or short thereafter. Don't leave the button out, as not everyone has JS enabled.


You could use a switch statement or an if statement using getGroups().

Instead of me taking all the credit, here is a great thread along with an example of using getGroups at the template level.

Here is what that might look like within a plugin.

To get the actual ID of the group - I'm sure there is a more scientific way, but If I'm always going to know what the ID is, I'll just hover over the handle and look at the url. It will be something like /settings/users/groups/2.

Hope this helps!


How do I find live and pending entries when using an array?

You can get all entries regardless of status with .status(null):

{% set allEntries =  craft.entries.section('sectionName').relatedTo(category).status(null).find() %}


How can you display entries filtered by localisation/localization?

Yeah, a simple checkboxes field with a list of the countries would be a good approach to realize this.

Another idea is to make use of the localization feature, which comes with a Craft Pro license. Then you'd add a new structure entry (in your case the product) in one locale (e.g. "fr"), save it, and all entered content is copied over to the other locales (e.g. "en" and "de").

After that you can switch over to another locale's version of that entry, and make individual edits for it (e.g. change "10 EUR" to "8 GBP"). To disable an entry completely for one locale, use the status lightswitch available for each locale separately at the top right of the info panel.

Don't read this as if this "localization feature" solution is the right one. Consider if you really need to translate entry fields (product infos etc.) into other languages1, if not I'd definitely do it like you initially intended.

And there's also a chance that you want to use both of these features combined: if you want to list all entry pages translated for each locale and additionally show the visitors where these products are available.

--

1. "Craft Personal and Craft Client store content on a per-locale basis too, so down the road if you want your site to cater to a second locale, Craft is already set up for it."


Plugin Development: intercept Entry before returned to template

Probably depends on the specifics of what you're trying to accomplish, but your best bets I'm guessing would be to listen to some of the element level events, make sure it's an entry and a site request, then do your logic.

onBeforeBuildElementsQuery, onBuildElementsQuery, and onPopulateElements are potential candidates.


How is a typical frontend request output generated?

Craft is an MVC application, so most requests initially will get routed to a controller action. Steps 3-6 in our Routing docs page show the various ways that the target controller action is decided.

Controller actions can really do whatever they want with the request at that point, but typically they will perform some level of authorization, and then either perform an action and/or define + send the response.

For example, if you request a template path directly, the request will get routed to the templates/render action, which will verify that the template actually exists, and then render and return it, otherwise throw a 404 exception.

Template rendering is ultimately performed by TemplatesService::render(), which is where Twig gets invoked.


How to Generate Unique Slugs for a Section without ticking "Entries in this section have their own URLs"

You should probably just set your event dates using custom Date/Time fields rather than the Post Date and Expiration Date fields. That way you don’t have to fight with Craft’s restrictions on non-live entries.


The answer is to create a custom plugin that will read the json files from the folders in the public directory, parse the json, and pull them into the template.

An alternative solution is to use Craft custom config files. (Not the answer you're looking for but would work very well.)

In craft/config create a file like localedata.php and make it something like this:

<?php

/**
 * Return an array indexed by locale code
 */
return [
    'ar' => [
        'serviceName' => 'arabic',
        'language' => 'ar',
        'textDirection' => 'rtl',
        'socialMediaButtons' => ['twitter', 'facebook'],
    ],
    'en' => [
        //...
    ],
    // etc
];

Then in your template you could do something like this:

{#
    If the current locale is `ar` (Arabic) then this will set `localeData`
    from the array index "ar" in the config file
#}
{% set localeData = craft.config.get(craft.locale, 'localedata') %}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="{{ craft.locale }}" dir="{{ localeData.textDirection }}">
<head>
  ...
</head>


The command line syntax for install without user input should be:

./craft install --interactive=0

There's a great article describing just such an automated approach here.


It means you've got a loop on an element query somewhere in your templates.  For example:

{% for entry in craft.entries.section('mySection') %}
    {{ entry.title }}
{% endfor %}

You should update it to use .all() like so:

{% for entry in craft.entries.section('mySection').all() %}
    {{ entry.title }}
{% endfor %}


Ever since Craft 1 launched in 2013, purchasing a Craft license (Client or Pro editions) has included free updates – even major releases, which means that your current Craft 2 site will be eligible for a free upgrade to Craft 3 once it launches in April 2018.

With the release of Craft 3, this will change: in order for your site to stay updated, you'll have to renew your Client or Pro license yearly, for a reduced fee ($39/year for Client edition, $59/year for Pro). If you opt out of renewing after the first year, you won't receive any further updates, but your license will still be valid and your site will still work.

Note that the yearly fee does not apply to any existing licenses, which will continue to receive free updates indefinitely.

Source: https://craftcms.com/news/dot-all-2017-announcements


Images lose quality when I upload to Craft

There is a way to get Craft uploading my pixel-perfect images without re-save them?

You can upload via FTP and then run the Update Asset Indexes tool from the Settings page in the control panel.

If you want to continue uploading from the control panel make sure that you're using Imagick instead of GD.

Craft will use Imagick if it is available to PHP by default or you can force Craft to use one or the other via the imageDriver config setting.


Is there an equivalent to IOHelper::ensureFolderExists in Craft 3?

In Craft 3, the IOHelper class has been replaced by the FileHelper class.

The closest Craft 3 equivalent to IOHelper::ensureFolderExists() is

FileHelper::createDirectory($path);


You can try to use craft plugin design by pixel & tonic as they are the best support with Craft CMS 2 and 3.


Here's what I did. You'll need to set sectionId first.

{% set thing = craft.sections.getSectionById(sectionId) %}
{{thing.getUrlFormat()|split('/')[0]}}


Error: "Variable "entry" does not exist" on basic template

In order to set an entry as your "homepage" entry you have to leave the uri in the section completely blank. It does not work when you insert a / because this route does not fetch the correct element thus Craft is not able to provide the entry variable in your twig template


How can I display just the "lowest" categories assigned to an entry and not parent categories?

I could not test it, but you could try:

If you always have a Parent and 2 levels

entry.businessTypes.level('>= 2').all()

If you want to only get the lowest, you could try to assign it with a condition:

{% if categories = entry.businessTypes.children %}
    {% set categories = entry.businessTypes.level('>= 2').all() %}
{% else categories = entry.businessTypes.children %}
    {% set categories = entry.businessTypes.all() %}
{% endif %}

{% for category in categories %} ... {% endfor %}


Is it bad practice to re-use array variable name?

There's no problem re-using a variable name from a technical point of view. There is likely a problem elsewhere in your code.


orderBy() should do the trick.
The docs show following syntax: .orderBy('elements.dateCreated asc')

Maybe something like:

{% set entriesList = craft.entries.section('parks')
   .relatedTo(entry.Line.one())
   .orderBy('elements.tableName.row(n).columnName asc')
   .all
%}


Posting front-end form to plugin controller route results in 404

You're getting a 404 because your action method isn't telling Craft what do to after it has echo'd 'Here', so routing continues.

See #3 is that link:

The request doesn’t necessarily end after a controller has been called. The controller may allow it to keep going.

You can redirect, end the request, load up a template to display, etc.

Update:

The controller folder needs to be renamed to controllers.


Show related entries without current entry

You're wanting to show a paginated list of related entries from a single entry page based on a tag relationship, correct?

This should point you in the right direction:

{% set segment = craft.request.lastSegment %}

{% for entry in craft.entries.slug(segment) %}

    {% set tagId = entry.myTagFieldHandle.first() %}

    {% set relatedEntries = craft.entries.relatedTo(tagId).id('not ' ~ entry.id) %}

    {% paginate relatedEntries as related %}

        {% for entry in related %}

            {{ entry.title }}

        {% endfor %}

    {% endpaginate %}

{% endfor %}


First a bit of history:

Craft 2 has a similar concept where it would store a unique random security key in craft/storage/runtime/validation.key.  Alternatively, you could set the validationKey config setting if you wanted to provide your own key instead of use the one generated by Craft.

Craft 2 would essentially only use this for encrypting cookie data in a browser for authenticated sessions.  Because everything in craft/storage/runtime is temporary and could be deleted at any time, it is important in load-balanced environments to use the validationKey config setting and set it to the same key for every web instance behind the load balancer.

It is possible that a plugin might go through craft()->security->encrypt(), which takes the key into account, someone nukes the validation.key file that lives in craft/storage/runtime and Craft is unable to decrypt the data at that point.

Craft 3 decided that it would probably need to start encrypting data in the database at some point in the future, so it needed a more reliable way to guarantee there was a security key it could use.

So craft/storage/runtime/validation.key was deprecated and moved to craft/storage/security.key, the validationKey config settings was renamed to securityKey and Craft 3 now requires it to be set in some form or another.

Craft 3 also added another way to set it if you use the composer starter project via the .env SECURITY_KEY environment variable, so that you can use 'securityKey' => getenv('SECURITY_KEY'), in your craft/config/general.php file.

Now to the questions:

  It has to be the same for one project, right?

It should be, if you want to reliably encrypt and decrypt data across environments.

  So it should be shared across developers.

It should be, if you want to reliably encrypt and decrypt data across developers.

  But is it a good idea to commit it to a Git repository?

Definitely not a public repository.  Arguable in a private one.

  Due to some circumstances I lost the security key of the initial installation and added a new one. Could that lead to unwanted behavior down the road?

You wouldn't be able to decrypt any data that was encrypted with the old key.

In the case of session cookies, the worst that would happen is you'd lose your current session.  In the case of encrypted database email settings, you'd have to re-save your email settings.  In the case that a plugin is doing some custom encrypting and decrypting and relying on Craft's craft\services\Security class to to it, you wouldn't be able to decrypt that data.


There may be a better way, including adding exclusions as an array and checking if the segment exists in the array, but what about wrapping it in an if tag? This seems to work.

{% if craft.request.firstSegment != 'contact' and craft.request.firstSegment != '404'  %}
    {% include 'layouts/partials/my-template'%}
{% endif %}

Quick update: This is very rough but an example with exclusions array (doesnt account for other segments, just an example...

{% set exclusions = ['contact','404'] %}
{% if craft.request.firstSegment not in exclusions  %}
    {% include 'layouts/partials/my-template'%}
{% endif %}


Programmatically entering data into a table field for an entry

When saving data to a Table field, here's the catch... Your field data is being condensed into JSON and stored in a single database table cell.

So ultimately, you'll want to have your Table field data arranged in an array, then use json_encode to prep it for entry into the database.

Here's an example of data for a Table field... This is a hypothetical field containing products, with a Product Name and prices for Small, Medium, and Large...

[
  {
    "col1": "Product #1",
    "col2": "5",
    "col3": "10",
    "col4": "15"
  },
  {
    "col1": "Product #2",
    "col2": "7",
    "col3": "14",
    "col4": "21"
  },
  {
    "col1": "Product #3",
    "col2": "7",
    "col3": "14",
    "col4": "21"
  }
]

An important note... The column names you established when setting up your Table field are not relevant here. Instead, each columnn will be referred to as "col1", "col2", "col3", etc.


You could try to use a task, to make sure the upload is completed before redirecting.

Here is a good starting point on how to use a task:
Documentation on creating tasks

Basically you define the steps of a task, in you case I guess 2. The next step of a task is started when the last step returned true.


Missing buttons in settings after update to 2.5 beta

Turns out that it was a badly written menu plugin, overriding styling of DOM elements outside of its own view scope. Sure it's related to Kyles suggestion above.


Creating a sitemap/index page, ordered by A-Z and 0-9

The way to do this is with the group filter. You want to group the entries by the first character of the title.

Get the entries as an actual array

{% set allEntries = craft.entries.section('artists').order('title').find %}

Group them by first letter of title. first will return the first character of a string. upper converts a string to uppercase.

{% set groupedEntries = allEntries|group('title|first|upper') %}

Now you can loop through them:

{% for index, values in groupedEntries %}

{{index}}

    {% for e in values %}

...{{e}}...

    {% endfor %}

{% endfor %}

See also this question.


Failed to add a custom field in settings

You're getting that error message because your PHP environment is displaying PHP Strict mode error messages.

By default, Craft will explicitly disable those if devMode is enabled (error_reporting(E_ALL & ~E_STRICT);) and disable all messages if devMode is disabled (error_reporting(0);).

So my guess is you've either got a plugin that's messing with error_reporting and re-enabling strict messages or you've doing it from your public index.php or craft/config files.

Note that in the upcoming Craft 3, we've made it so that you can run Craft with PHP strict error messaging enabled.


Update User "Field Type" for Entry in Plugin

When a User field is saved, it takes an array of user IDs only – not complete UserModel objects. Something like this should work:

// get IDs for current members of group
$members = $entry->members->ids();

// add new user ID to members
$members[] = $addUser->id;

// update field with new $members array
$entry->getContent()->setAttribute('members', $members);

The rest of your code looks fine, except for a minor typo – $enries should be $entries.


Using data within a mixed attribute type to query Craft entries dates

Just in case anyone else comes across this problem in the future I actually managed to figure it out myself.

I created kept the fieldtype as a DateTime field and grabbed the date/time and the extra value within the prepValueFromPost function then pushed the extra data into a custom table and post just the datetime to the craft_contents table.

Then within the getInputHtml function I grabbed the extra data from the custom table to display along with the date/time.


This should get you the desired results:

{% for entry in craft.entries.section('yoursection').order('startDate desc, featured desc') %}

    {# Entry Code #}

{% endfor %}

If for any reason that doesn't achieve exactly what it is you are looking for, you could always break it up into multiple loops, 1 for featured, and 1 for not featured. It's not as clean as the above solution but should also solve the issue:

This will use 2 loops, one for the featured and 1 for the not featured, assuming the 'featured' field is a lightswitch.

{% for entry in craft.entries.section('yoursection').search('featured:1').order('startDate desc') %}

    {# Entry Code #}

{% endfor %}

and

{% for entry in craft.entries.section('yoursection').search('featured:not 1').order('startDate desc') %}

    {# Entry Code #}

{% endfor %}


Bypass server memory_limits for Cloud Asset resources

I don't think there is anything native in Craft that is going to help you here.

FTP is probably the best bet.  Only images get downloaded from external sources during indexing, so it's a simple as FTP'ing up the files and rebuild the asset source indexes (which could be automated via cron job).


onBeforeSendEmail event triggered from Commerce_EmailsService

You don't show what code you're trying to use to access the parameters, but something like this should work from your main plugin class:

public function init()
{
    parent::init();

    craft()->on('commerce_emails.beforeSendEmail', function($event) {
        $params = $event->params;

        $craftEmail = $params['craftEmail'];
        $commerceEmail = $params['commerceEmail'];
        $order = $params['order'];
        $orderHistory = $params['orderHistory'];

        ...
    });
}


Mcrypt is required on OS X Mavericks 10.9.4

Here's all you need:

http://topicdesk.com/downloads/mcrypt/mcrypt-download

Works like a charm.

Update: to use brew, you have to specify the version of PHP for it to work. For example:

brew install mysql php54-mcrypt


How can I filter Craft Commerce products by the current price

https://craftcommerce.com/docs/variant-model#saleprice

The comment on the documentation leads me to believe you can just use salePrice for your filtering as it will be equal to the defaultPrice if there is no sale.

So:

{% set queryParams = {
        relatedTo: category,
        salePrice: [
            'and',
            '>= ' ~ 0,
            '<= ' ~ 90,
        ]
    }
%}


The short answer is yes — you need to use a domain names.

You might also want to have a look at this multi-environment configuration method defined on the craft cookbook website that creates a global php variable called CRAFT_ENVIRONMENT in your main index.php.

I generally use that in combination with Ben Parizek technique as described in this answer.


Pagination returns a result after last page has been reached

You can detect if the requested page is greater than the total available pages for the current list of entries like so:

{% paginate entries as entriesOnPage %}

    {% if craft.request.getPageNum() > paginate.totalPages %}

No results

    {% else %}
        {% for entry in entriesOnPage %}
            ...
        {% endfor %}
    {% endif %}

{% endpaginate %}

Rather than displaying a message, you could also choose to put an {% exit 404 %} tag in there.


Sorry, it was a dumb question, I just missed the greyed out checkbox with sources in the field settings.


Setup a dynamic route that points to the same template that you have set up in the section settings for your "slug URLs". Use a pattern like so: news/<id>, which passes the 2rd URL segment as a variable named id to the template.

Add this snippet to the top of your template.

{% if not entry and id %}
    {% set entry = craft.entries.id(id).first() %}
{% endif %}

{% if not entry %}
    {% exit 404 %}
{% endif %}

If Craft finds a route for your entry slug (routing case 3), that code does nothing at all, because the entry model is already set.

When no route was found that matches an entry slug, your dynamic route comes into play (routing case 4), which routes the request to the same template.
But now there is no entry variable set and we can go ahead and try to grab it manually using the id variable passed in.

Update:
as already mentioned in the comments, don’t forget to setup canonical meta tags to avoid duplicate content penalties.

<link rel="canonical" href="{{ entry.getUrl() }}">


Fields in craft that are not element is query by something called element criteria model.
In twig you do:

{% set result = craft.entries({
       section: 'boxes'
       orderBy: 'dateCreated asc'
       year: year,
       quarter： quarter
}).all() %}

In php

 $query = [
        'year' => $year,
        'quarter' => $quarter,
    ];
 $seasonBoxesQueryObject = \craft\elements\Entry::find()
                 ->section('boxes')
                 ->orderBy('dateCreated asc');
 $seasonBoxesQueryObject->year = $query['year'];
 $seasonBoxesQueryObject->quarter = $query['quarter'];
 $seasonBoxes = $seasonBoxesQueryObject->all();


Yes. It is possible, you need to specify the craft category and set the group parameter on it and fetch the categories with .all().

{% set categories = myCategoryQuery.all() %}


How do I print the options in a dropdown field?

There's not an "elegant" way to do this but you can access the dropdown field by its handle using getFieldByHandle. Something like:

{% set dropdownField = craft.fields.getFieldbyHandle('isotope') %}

  {% for option in dropdownField.settings.options %}

{{ option.value }}

  {% endfor %}

If you need the label instead, just use {{ option.label }}

You can also grab a dropdown's options from any entry you know has the field already attached, such as the first entry from your news section for example:

{% set entry = craft.entries.section('news').limit(1)[0] %}

{% for option in  entry.isotope.options %}

{{ option.value }}

{% endfor %}

Note: similar to this question.


What could the possible causes be for a mismatch between `craft_fields` and `craft_fieldlayoutfields` MySQL tables?

Craft doesn’t do any field operations in the queue, so it must be the first option.

Create a DB backup first, but it should be safe to delete the rows for fields that are not in the Matrix field’s layout. It also wouldn’t hurt to double-check the matrixcontent_modules table to make sure it doesn’t have columns for those fields.

Also worth noting, you can shrink the size of the table by going over all the sub-fields and checking their Column Type settings (under Advanced). If it’s possible to select smaller column types, you should do it.


Include a template that sets variables (global template variables)

There are actually two issues with this approach. The first, and the direct reason you’re getting that Twig error, is that templates that extend another template can only output things within {% block %} tags. Any HTML that gets output outside of those tags (either directly or via {{ output tags }}) will result in that Twig error.

The {% include %} tag is in the same boat. Its only purpose (as far as the parent template is concerned) is to output the results of a child template. So like {{ output tags }}, you can’t place it outside of {% block %} tags. If you really want to include a template within these nested templates, you will need to move it to within your {% block %}.

Even if you did that, though, you’d then run into the second issue: Any variables that are set/modified within an included template will not bubble back up to the parent template. For example, if you had these two templates:

parent template:

{% include "_inc" %}
{{ foo }}

child template (_inc.html):

{% set foo = 'bar' %}

That foo variable would actually be discarded as soon as Twig was finished rendering _inc.html; nothing that happens in there will have any effect on the parent template. (As I said, the only purpose of the {% include %} tag as far as the parent template is concerned is to output the rendering result of the included template.)

However, it’s still probably possible to achieve what you want when you consider the order in which these templates are going to be processed:

Everything besides the {% block %} tags in the requested template (the one with the {% extends %} tag)
The layout template (_layouts/default.twig), including its {% block %} tags
The requested template’s {% block %} tags

Knowing that, you can probably just set your variables you’re trying to set from within _layouts/default.twig, and they will be available within the requested template’s {% block %} tags.

requested template:

{% extends '_layouts/default.twig' %}

{% block content  %}
    {{ foo }}
{% endblock %}

layout template (_layouts/default.twig):

{# Set the variables you were trying to set in _resources/variables.twig #}
{% set foo = 'bar' %}

{% block content %}
{% endblock %}


Where should PHP file of custom widget be in?

If it were my project, I would probably put the PHP file in modules

Here's some more info https://docs.craftcms.com/v3/extend/ and here: https://docs.craftcms.com/v3/extend/module-guide.html


It sounds like you need to create a dynamic route by going to Settings > Routes > "New Route".  Then you'd set your custom route to profiles/{slug}/email-signature and decide which template to serve when the url looks that way.

You can either serve the _entry template you're serving for /profiles/john-doe or create a new one. Depending on the situation, you may need to set the entry in the template like...

{% set person = craft.request.getSegment(2) %}
{% set entry = craft.entries.section('profiles').slug(person).first %}

...in the event Craft can't figure it out because you're on a separate template.  Grabbing segment 2 means you're grabbing john-doe from the URL, which will help Craft know which entry to find.

Here's more info on routing in the docs: https://craftcms.com/docs/routing#dynamic-routes


PHP error when trying to access dates in Sprout Reports

You can't access date this way, you'd need to use the date (docs) or datetime (docs) or even atom (docs) filters.
In the case of your report, since you have multiple conditions, you would need to pass those as an array and use the atom filter.
Try:
{% set purchases = purchases
    .postDate([
        'and',
        '>=' ~ settings.datetimeStartDate|atom,
        '<= ' ~ settings.datetimeEndDate|atom
    ]) %}

Alternatively, you can use before() (docs) and after() (docs) and pass date objects directly:
{% set purchases = purchases
    .after(settings.datetimeStartDate)
    .before(settings.datetimeEndDate) %}


Can I open templates/routes other than 503 when Craft is offline?

I don't think it's possible using the System Status switch in Settings → General.

I had a similar requirement and solved it with a custom variable "maintenanceMode" in my config.php and added some simple logic to the init method in my business logic plugin, which redirects all request except some maintenance mode URLs to the 503 page.

$maintenanceUrls = array('/503', '/impressum', '/about');

if (craft()->request->isSiteRequest() && craft()->config->get('maintenanceMode')) {
    if (!in_array(craft()->request->getUrl(), $maintenanceUrls)) {
        craft()->request->redirect('503');
    }
}


if you've already set up a volume with your local assets, you can set up another one for s3 and simply drag and drop them over in the "files" section.


All categories selected by default for an entry

There's not a native way to do this, but you could probably pull it off in a plugin that utilized the cp.entries.edit template hook and modified the field data directly (selecting whatever categories you want) before returning it to the template.


You've got a quote in the wrong place.

This...

{% "include _views/reviews.twig" %}

should be this...

{% include "_views/reviews.twig" %}


Add custom attribute to standard element from plugin

Another approach is to use the following event to attach a behavior

Event::on(Asset::class, Asset::EVENT_DEFINE_BEHAVIORS,
function(DefineBehaviorsEvent $event) {
    $event->behaviors[] = MyBehavior::class;
});

The behavior could look like

class MyBehavior extends Behavior {
    public $downloads;
}

This way you won't receive an exception and can access your property via

$asset = Assets::find()->all();
$asset->downloads;

You can as well manipulate the value of downloads in the Behaviors init function in order to return the file or something like this


Craft 2.3 new User does not set the default permissions group

The setting still works, but keep in mind that for it to take effect, A) you have to be registering a user through a custom registration form on the front end, and B) you have to be logged out. Without those conditions, it’s not technically public registration.

Default user group assignment has always taken place after the user was saved, and after the users.onSaveUser event was called. See these highlighted lines from UsersController::actionSaveUser() – the onSaveUser event gets called by craft()->request->saveUser(), and default group assignment happens in $this->_assignDefaultGroupToUser().


Currently the images are being cleansed on upload, which means that they are being re-saved to make sure that no malicious code is injected in them.

Unfortunately, this means that EXIF data gets stripped out along the way, but since Craft already uses PEL, it should be possible to tweak Craft a bit so that the EXIF metadata is preserved during this operation. We'll look into that and, hopefully, this will make it to a release pretty soon.


Commerce: How to implement/save 'Use shipping for billing' field for future orders

We achieve this by simply checking the ids of the addresses set on the cart.  Commerce saves the last used shipping and billing address for customers, so you can just use some simple template logic to achieve what you want I think:

        {% set sameAddress = true %}
        {% if cart.shippingAddress and cart.billingAddress %}
            {% if cart.shippingAddress.id != cart.billingAddress.id %}
                {% set sameAddress = false %}
            {% endif %}
        {% endif %}

        <div class="same-address-checkbox">
            {{ forms.inputCheckbox({
                type: 'checkbox',
                id: 'sameAddress',
                name: 'sameAddress',
                checked: sameAddress,
                value: '1',
                label: 'Use same address for billing address?',
            }) }}
        </div>

One caveat here, if you offer a checkout during registration, you'llw ant to use my plugin for this as otherwise these last used addresses are not copied to the newly created Craft user - https://github.com/bossanova808/CommerceRegisterOnCheckout


Change page elements based on geolocation

Let's get the easy question out of the way first... Don't use Craft's localization to handle this task. While the localization feature is amazing and powerful, it doesn't fit the needs you're describing. Localization is mainly geared towards handling different languages for different countries.

So what's the best way to handle this? Fortunately, it sounds like you've already worked out the hard part:

  I actually have the PHP working well to pull the 2-letter state value from a Geocoding API

All that's left now is to integrate that business logic into your Craft site! There are a few different ways to approach this, but I'll lay it out in a way that's simple, straightforward, and best fits your current scenario...

Grab and install the Business Logic plugin (unless you've already got a custom plugin installed, in which case you can just build on that).
Create a new function in the Variable file. Let's name it something like detectState.
Put all of your existing PHP logic into that function. You can even get, set, and check your cookies straight from this function. Using a separate cookie plugin may not even be necessary in this situation, since it's easy to manage cookies directly from PHP.
Have your function return the 2-letter state code.
In Twig, you'd call your new function similarly to this:

{% set stateCode = craft.businessLogic.detectState %}

Voila! You can now use stateCode to handle whatever Twig switching logic you need.


"Could not find composer.json file" error in CraftCMS 3

You need to open your index.php file and add composer path line.
E.g. my composer.json file is placed in root folder and I defined below path inside my index.php:
    <?php

//Project root path
$root = dirname(__DIR__);

// Load and run Craft
define('CRAFT_BASE_PATH', $root.'/craft');
define('CRAFT_COMPOSER_PATH', $root.'/composer.json'); <======= this line
require_once $root.'/vendor/autoload.php';
$app = require $root.'/vendor/craftcms/cms/bootstrap/web.php';
$app->run();


Add field to /settings/sites/new (multi-site)

If I'm following you correctly, there currently isn't a way to do this.

Sites are a concept that doesn't support things like fields and field layouts like other elements (Entries, Categories, Matrix Blocks, Tags, etc.).


Sorting an array of entries according to a fixed list/array of items

Edit: This strategy still works, but see my updated answer for more up-to-date solution.
Prior to SuperSort 3.1.0, you might achieve this by using the replace filter inside SuperSort's micro-template:
{% set foo = craft.entries.section('foo')... %}

{% set sortedFoo = foo | supersort('sortAs', '{ shopType | replace({
    'ShopType1': "A",
    'ShopType2': "B",
    'ShopType3': "C"
}) }') %}

The first parameter you pass to SuperSort specifies the sort method.
The second parameter provides a value template for the sorting function: Under the hood, the system parses { shopType | replace(...) } — a Craft 'micro-template' — into {{ object.shopType | replace(...) }}. The plugin parses that template by passing in your array item as the object and uses the output value to sort by.)
n.b. You need to specify that replacement list directly in the object template. Passing in a Twig variable doesn't work because the object template doesn't share the same context as the parent template.
The syntax in your original question would actually not be a bad addition for use-cases like this; I'll look into adding something like that to SuperSort when I get some downtime.
As of SuperSort 3.1.0, you can now use a custom-order sort method, similar to what you originally suggested.


Help with tags input field on a front-end entry form

First of all generally it's a really good idea to check how Pixel and Tonic has handled all the things. I know many people tend to dislike this hint but it's the best thing you can do. The developers are really good, they make good and useful comments and - at least for Craft 3 - they take care of the PHP Doc (in Craft 2 too but not as well)

When I run into issues/trouble the first thing I usually do is do dig into the well documented source code and check what they did.
As far as I can see in your question you already started to do that too which is great.

Maybe I'm just too paranoid but you should never delete or insert something without checking it and of course you should not leave tags in your DB either. Your page could become slow if you don't remove them. The best thing to do: check if the tag is used in your controller and delete it if it has no relations/uses after the jQuery remove callback. That leads me to my next hint: many people try to avoid a custom controller but mostly it's so much easier to use Crafts/Yiis power instead of trying to avoid work.

Like you already stated you could spend multiple hours to search for a good jQuery plugin to avoid 2-3 lines of php code or you can just extend the EntriesController, copy the save function and include a few lines to deserialize the tag input. I don't really use jQuery (only angular) so I can't suggest you a plugin for that but as soon as you create a custom controller you are free enough to use the plugin you like and not the one that avoids php.

However - what I would suggest is the following.

Find a jQuery plugin that has the following callbacks afterInsert to upload the tag via ajax, afterRemove so you can delete tags and maybe something that allows autocomplete
Create a function to search for tags in your controller, this is for autocomplete. You'll want to return an array of possible tags that match your users input
Create a saveTag function in your controller, check if the tag already exists, if so return the ID if not create a new one and return the ID. If the tag is created via autocomplete you won't need an additional Ajax request since you'll fetch the ID with the tag name
Insert the ID in a hidden input
Create a deleteTag function and check if the tag is used somewhere. This part is mostly copy paste. You want to take a look how Pixel and Tonic did it and copy the functionality with minor changes here and there to fit your needs
Copy the entries save function and insert it in your controller. At the beginning of this function you could explode the single, comma sparated hidden input into an array and that's basically it.

That's the way I handled it the last time - only with angularjs instead of jQuery


How can I add a favicon to the admin part of Craft?

If you go to Craft Settings > General you can add a site icon in there plus a logo for the login page.


Remove expiration date field from section / entry type

I'm not aware of any straightforward way to remove that field from the Entry form. You might want to consider creating a small site module, adding some logic in an event handler to re-write/remove the contents of the expiration date as necessary?


Getting Service Unavailable when setting up domain name

Have a look at this document: https://craftcms.com/docs/multi-environment-configs

You can configure it differently for local, staging, production, etc, by the name of the domain name


Missing Matrix row types on output after upgrade to Craft 3 (subsetting and cloning ElementQueries)

Turns out my issue is because I am running 2 loops through entry.timeline:

A subset of the field with only subsection blocks to generate a table of contents
The entire field contents with a mixture of both subsection and item block types.

Craft 2 was totally OK with me defining a subset and then looping through the entire set, but with Craft 3, if the subset is defined first, it seems to persist when the second loop runs, even if the scope of the second loop is defined differently.

So my current solution is to have a template structured like this:

{# Fetch the entire set first even though it will run second #}
{% set timelineItems = entry.timeline.all() %}

{# Fetch the subset second even though it will run first #}
{% set tocItems = entry.timeline.type('subsection').all() %}

{% for item in tocItems %}
    {# do subsetted ToC stuff #}
{% endfor %}

{% for row in timelineItems %}
    {# do entire timeline stuff #}
{% endfor %}

See https://github.com/craftcms/cms/issues/2160 for more background, and cloning element queries in the docs.


Monthly subscription with Stripe using iDEAL

Have you tried having a look at the API Docs for Stripe? They have written about ideal integration:

https://stripe.com/docs/sources/ideal

If its in your budget you should probably also have a look at Craft commerce which has partial Mollie integration which should, in turn, facilitate the iDeal payments solution that you are looking for. Though they do say it is only partially supported so you may need to investigate if this is exactly what you are looking for.


How to get a list of unique related entries from within a related entries loop

How about this?

{% set uniqueLocations = craft.entries.section('locations').relatedTo(mockExams).all() %}

{% for location in uniqueLocations %}
  {{ location.title }}<br />
  {{ location.address }}
{% endfor %}


Seems pretty straightforward, unless I'm missing something.

Create the 6 locales; one for each location (settings > locales)
Create user groups (10) and set permissions (settings > users)

Allow location drafters to only 'edit' and 'create', but not 'publish' (for each section)
Restrict location drafters to their respective locale (single locale)
Allow Region Admins to edit, create, and publish (for each section)
Restrict Region Admins to their region locales (more than one locale)
Allow Super Admins to edit, create, and publish (for each section)
Allow Super Admins for all locales

This is assuming of course you have a locale for each location (and not for each region).


Issues upgrading Craft 2 to 3 - Keep seeing Install Screen not Update screen

If you've seeing any install screen instead of an update screen, that means that Craft can connect to the database server specified in craft/config/db.php file, but it either can't find the database you've specified or it can't find the craft_info table.  A common cause of this is the tablePrefix database config setting changed, for example.


How can I use CSRF protection with AJAX routes?

Disabling the CSRF protection is probably a bad idea... it's in there for a reason. But you can easily add your CSRF data to an AJAX call, and it works very well!

The key is to make your CSRF token name & value available in your front-end JS. You can then pass that into your AJAX call as an additional value.

There are a few ways to push the CSRF data to the front-end, so this is simply one example:

{% set csrfToken = {
    csrfTokenName: craft.app.config.general.csrfTokenName,
    csrfTokenValue: craft.app.request.csrfToken,
} %}

<script type="text/javascript">
    window.Craft = {{ csrfToken|json_encode|raw }};
</script>

Once you've got those values on the front-end, adding them to your AJAX call is relatively easy:

$(function(){
    var data = { id: 100 };
    data[window.Craft.csrfTokenName] = window.Craft.csrfTokenValue; // Append CSRF Token
    $.post("/actions/gistClient/exampleAjax", data, function(response) {
        console.log("success", response, data);
    });
});

That's it! Your AJAX call should now submit properly.


User activation success page localization problem

When you register/save the user you need to set their preferredLocale, so Craft adjusts the verification URL sent with the activation email accordingly. Craft uses the primary locale for a user who doesn’t have a preferred locale set.

You can do this using a hidden input field in the registration form, or via a users.beforeSaveUser event listener.

<input type="hidden" name="preferredLocale" value="{{ craft.locale }}">

Once your users have a preferred locale set, your localized activateAccountSuccessPath config should work.


How can I determine which user triggered an update?

That one is tricky.

I can't think of anything that gets logged in Craft's log files currently that would help determine that.

We do keep track of the request IP address in all of our web service logs, so if you wanted to send the domain along with the approximate update time to support@craftcms.com, we could at least send over the IP address the update was triggered from.  That won't help much if the person was sitting behind a proxy/DHCP server, though.


How to set up multi-env in Craft 3 with .env files?

These are the two approaches I usually choose from:

Option 1: the 'default' Craft 3 way

Create a .env file for every environment you create, and add it to your .gitignore file (if it's not yet in it). In this file, you put all environment-specific details;
Craft, by default, will recognize and use those details.
In your Craft config files, you can use the ENVIRONMENT as defined in your .env file to adjust the settings for one specific environment. So, the config that applies all the time is set in an array with the key '*', and the config that's specifically for the dev environment, is in the array that has the 'dev' key (If you use the default general config file)

Option 2: the .env.php way

One of the reasons this approach exists, is that the makers of PHP dotenv (used in option 1) 'warn against using it in production' (as quoted from the README of option 2). The method as linked in the title uses a PHP file and some minor alterations to your config and index files to let you maintain a multi environment build.


Something like this?

{% for marker in event.eventMap.getMarkers() %}
    {% set mapId = 'map' ~ loop.index %}
    <div class="google-maps">
        {% set options = {
            id: mapId,
            width: '100%',
            height: '150px',
            options: {
                disableDoubleClickZoom: true,
                maxZoom: 15,
                minZoom: 5,
                scrollwheel: false
            }
        } %}

        {{ craft.googleMaps.map() }}

        {{ craft.googleMaps.data(mapId, event.eventMap) }}

    </div>
{% endfor %}


For each entry, you can get the username of the author by simply using {{ entry.author }} (assuming entry is the variable containing the blog entry).

If you want to display Full name, first name and/or last name for one entry, you'd use:

{{ entry.author.fullName }}
{{ entry.author.firstName }}
{{ entry.author.lastName }}

For a list of entries and their authors, you'd use:

{% for entry in craft.entries.section('your-section').find() %}
    {{ entry.author.fullName }}
{% endfor %}


Input Tags Template for my Custom FieldType

You could use Select2 to search in a select field

$(document).ready(function() {
    $('.my-custom-awesome-select-class').select2();
});

All you need to do is to include the js file via asset bundle or register it in your view directly and execute the JS code


Adding a mailing list subscribe to contact form

There isn't a native way to to do that... it would have to be done with a plugin.

I'm not sure if there is an existing one, but Straight Up Craft currently has the most up-to-date list of available Craft plugins, so that would be a good starting point.


Sideloading an image from a function in a plugin

You can see an entire example how to fetch a file via curl, save it into an asset and relate it to an entry here

// get the entries service
$entries = Craft::$app->getElements();

// get the entry
$entry = \craft\elements\Entry::find()->one();

// somehow grab the path of your image
$client = Craft::createGuzzleClient();
$response = $client->get('https://www.google.com/logos/2018/halloween18/rc5/cta.png');

$image = $response->getBody()->getContents();
$path = Craft::$app->getPath()->getTempPath() . DIRECTORY_SEPARATOR  . 'someFile.png';
FileHelper::writeToFile($path, $image);

// the folder for the image
$folder = Craft::$app->getAssets()->getFolderById(1);

// create a new asset
$asset = new \craft\elements\Asset();
$asset->tempFilePath = $path;
$asset->filename = 'someFileName.jpg';
$asset->title = 'someTitle';
$asset->newFolderId = $folder->id;
$asset->volumeId = $folder->volumeId;
$asset->avoidFilenameConflicts = true;
$asset->setScenario(\craft\elements\Asset::SCENARIO_CREATE);
if($entries->saveElement($asset) === true){
    // file was saved
    $entry->setFieldValue('assetFieldHandle', [$asset->id]);
    $entries->saveElement($entry);
}


How do I fix getTemplatesPath() / setTemplatesPath() deprecation errors?

PathsService::getTemplatesPath() and setTemplatesPath() were deprecated in Craft 2.6.2778. They were commonly used by Craft and plugins to render front-end templates from the Control Panel (or vise-versa).

We realized that there were cases where simply changing the root templates path was insufficient to emulate front-end requests in the CP, though. For example, if defaultTemplateExtensions was being overridden to:

'defaultTemplateExtensions' => array('htm'),

and the CP was trying to find a “test” template which was supposed to resolve to test.htm, a CP request would not actually be able to find the template, because CP requests are only looking for templates that end in .twig and .html.

So in 2.6.2778 we’ve resolved this with “template modes”, which provide an explicit way to tell Craft to render a front-end template vs. a CP template, rather than simply telling it to use a different base template directory.

Updating your plugin code is pretty simple. Just change things like this:

$oldPath = craft()->path->getTemplatesPath();
craft()->path->setTemplatesPath(craft()->path->getSiteTemplatesPath());

// ...

craft()->path->setTemplatesPath($oldPath);

to this:

$oldMode = craft()->templates->getTemplateMode();
craft()->templates->setTemplateMode(TemplateMode::Site);

// ...

craft()->templates->setTemplateMode($oldMode);


Why would Craft Commerce only be using the dummy gateway?

If you are in development mode then Craft Commerce will still use the dummy gateway. You need to disable dev mode to allow your payment gateway to be used.


The easiest way is to use a GUI MySQL client to connect to the Craft database and edit the table directly.  Popular ones include Navicat and Sequel Pro, but there is a good list here of options for both OSX and Windows.

Once you connect to the database, you can edit the data in the craft_tasks table and change the value of status from running to pending to re-trigger it.


Craft 2.5 option to embed image with transform missing

This is a bug that has been fixed in the next (post 2.5.2750) release.


You can set a cookie from your template, which assigns visitors to specific groups:

Craft 2: (Use the LJ Cookies plugin)

{% set testGroup = craft.lj_cookies.get('group') %}

{% if not testGroup %}
    {# New user - assign them to a group at random #}
    {% set testGroup = random(['a', 'b']) %}
    {% set expires = now|date_modify('+30 days').timestamp %}
    {% do craft.lj_cookies.set('group', testGroup, expires) %}
{% endif %}

Craft 3:

{% set testGroup = craft.app.request.cookies.get('group') %}

{% if not testGroup %}
    {# New user - assign them to a group at random #}
    {% set testGroup = random(['a', 'b']) %}
    {% set expires = now|date_modify('+30 days').timestamp %}
    {% do craft.app.response.cookies.add(create({
        class: 'yii\\web\\Cookie',
        name: 'group',
        value: testGroup,
        httpOnly: true
    }) %}
{% endif %}

And then reference that testGroup variable whenever you need to know which group they’re in:

{% switch testGroup %}
    {% case 'a' %}
        ....
    {% case 'b' %}
        ....
{% endswitch %}

Nice thing about this approach is that you can actually have multiple sets of test groups at the same time, using different cookie/variable names. You’re also not limited to two groups per set.


Cannot change cart email within Craft Commerce while logged-in

I don't think there is an easy workaround here as you're dealing with logged in user functionality, and by definition that's not really designed to be easy to workaround.

Probably the easiest thing is for the admin to use the 'log in as XXX' functionality, and then complete the order for the customer (assuming the customer had a Craft account which is not, per se, a given with Commerce).  If they're guest customers, the admin should probably jsut log out, complete the order as a guest, and then log back in, basically.

Order entry for admins (via the backend) is on the Commerce plans, though, so a better solution may well appear.


How to get an entry title and URI from a segment in order to create a breadcrumb navigation

If your site is mixture of singles, structures and channels then there is no easy way to get the entry titles and or uris from the segments alone. You would have to add some logic based on your known site structure. And even then, you might need to make a lot of requests to retrieve the data. You would likely need to do a combination of static logic, looking up titles and uris based on section/handle, and looping through ancestors within a structure.

You could potentially use the segments themselves, if you where confident that the slugs always matched the titles (or were close enough), and that the uri's where all valid.

{% set segmentUri = "/" %}
{% for segment in craft.request.segments %}
    {% set segmentUri = segmentUri ~ "/" ~ segment %}
    <a href="segmentUri">{{ segment|replace('-',' ')|ucwords }}
{% endfor %}

There is also another technique that involves defining the breadcrumb using an entries field on the entry itself that you might consider — which is described in the documentation on How to create Breadcrumbs.


Order entries by multiple matrix date field

The quick and easy answer would be to just add the Twig sort filter to your startDates array. e.g:
{# Query entries that have training dates #}
{% set allEntries = craft.entries
    .section('trainings')
    .with('trainingDates')
    .trainingDates(':notempty:')
    .all()
%}

{# Merge all training dates in an array #}
{% set startDates = [] %}
{% for entry in allEntries %}
    {% for training in entry.trainingDates %}
        {% if training.startDate | date('d mm Y') not in startDates %}
            {% set startDates = startDates | push(training.startDate | date('d mm Y')) %}
        {% endif %}
    {% endfor %}
{% endfor %}

{# Show all trainings grouped by date#}

    {% for startDate in startDates|sort %}

{{ startDate }}

                {% for entry in allEntries %}
                    {% for date in entry.trainingDates %}
                        {% if date.startDate | date('d mm Y') == startDate %}

{{ entry.title }}

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

    {% endfor %}

(I've also added eager loading to improve performance).
You could potentially attack the problem from the opposite direction by using a matrixblock element query like this:
{# Query matrix blocks that have training dates #}
{% set matrixBlocksQuery = craft.matrixBlocks().field('trainingDates') %}
{% set uniqueDatesSorted = matrixBlocksQuery.all()|map(block => block.startDate|date('d mm Y'))|unique|sort %}

{# Query entries that have training dates #}
{% set allEntries = craft.entries
    .section('trainings')
    .with('trainingDates')
    .trainingDates(':notempty:')
    .all()
%}

{# Show all trainings grouped by date#}

    {% for startDate in uniqueDatesSorted %}

{{ startDate }}

                {% for entry in allEntries %}
                    {% for date in entry.trainingDates %}
                        {% if date.startDate|date('d mm Y') == startDate %}

{{ date.id }}{{ entry.title }}

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

    {% endfor %}

...but to be honest I think I prefer your approach, as it's more readable and doesn't require an extra .all() query to get the dates


Craft 3 / Sprout Forms Bootstrap field classes

In Craft 3, you can do this by overriding the field inputs directly, and you shouldn't have to add any logic to the form, tab, or fields templates. We're still working on getting the docs updated to properly show this.

Custom Form Templates

To override field inputs in Sprout Forms, you can enable Form Overrides in your settings.

  Sprout Forms->Settings->General->Default Form Templates->Custom

Here you can define an override folder in your front-end templates. Let's say you set your default templates to _forms. This means your override templates will exist in templates/_forms.

Once you have that in place, you can place a fields folder within that folder that contains a field override:

templates/_forms/fields/dropdown/input.html
templates/_forms/fields/email/input.html

You can do this for all the fields where you wish to modify the base input HTML.

A good place to start may be to copy the code for the specific field you wish to override from Sprout Forms itself:

https://github.com/barrelstrength/craft-sprout-forms/tree/v3/src/templates/_formtemplates/fields

Making Your Form Templates into a Plugin

If you like the templates you've created and wish to reuse them on more than one project, you can take what you've done above and wrap it in a plugin.

Creating a Form Template integration will display your Form Templates in the dropdown list of Templates to choose from. The template files themselves would then be managed in your plugin instead of in your project.

You can see an example of how to create an integration in Sprout Forms with the AccessibleTemplates Form Templates:

https://github.com/barrelstrength/craft-sprout-forms/blob/v3/src/integrations/sproutforms/formtemplates/AccessibleTemplates.php

The integration is really just a way to tell Sprout Forms where your form templates are and makes it easier for content editors to select in the Craft UI.


Until the plugin store officially becomes a thing, the most up-to-date list of plugins available for Craft is here.

I'm not seeing anything that does exactly what you're looking for and Craft doesn't have that functionality natively, but it doesn't seem like too difficult of a plugin to write.


299US$ Upgrade for Pro is for 1 site or any domain with my License

It is per domain (excluding sub-domains), i.e. for one domain / website.

domain.com and subdomain.domain.com can both run off of the same license.

More info on how that is all enforced.


The answer: after you create a "select field", name it whatever you want - in this case country - and then add it to a form. Once you have done that, select that field within the form and edit in the properties column. Under Option Editor > Source, select "Predefined Options", then under > Target, select the option set you want, e.g. Countries, States, etc.
Seems to me that this should be part of the field creation process, rather than doing it in the form, but once you understand how to do it, it works great.


Is it possible to extend twig with 'Twig_SimpleTest'?

When you call Craft's TemplatesService->getTwig() (craft()->templates->getTwig()), you get an instance of the Twig environment and from there you could be able to call addTest.

100% untested, but something like this should work:

$twig = craft()->templates->getTwig();
$twig->addTest(new My_Twig_SimpleTest());


I'm afraid Craft 3 requires PHP 7. https://docs.craftcms.com/v3/requirements.html

Craft 2 will work with older PHP versions  (5.3 to 7.1.x) so you could fall back to using that. https://docs.craftcms.com/v2/requirements.html

Other than that, I'd say you would need a different host in order to run Craft 3.


I selected all in _product.twig and cut and then refreshed the page. Got a blank screen. I then pasted back in and it fixed the page. This was after emptying browser cache twice and trying different browsers that I hadn't previously used on the site. Odd but that fixed it. I was going to delete this post but decided to leave it in case anyone else has this problem. This was developing the site locally, using MAMP and gulp and Tailwindcss.


You can also check out the free video on it here: Using Craft CMS 3 Multi-site

Multi-site has changed as of Craft 3 RC11. It now requires much less config outside of the control panel. See the official docs on Sites in Craft 3.


Two plugins contain the same function name so they're conflicting

You could get around this by creating your own renamed copies of those functions.

Create a module.
Copy the content of each affected plugin's twigextensions folder to your module's twigextensions folder.
Adjust the namespaces in these files to match your module
Rename the functions / filters in these files to something unique.
Load these twigextensions in your module's main file (use statement plus Craft::$app->view->registerTwigExtension).
You can now use the filters in twig by referencing the unique name you gave them.

If you haven't worked with modules before, you can use pluginfactory.io to scaffold a module that includes lots of example code, including all the required code to set up a twig extension.

To improve on this further, instead of a straight up copying of the twig extensions, refactor them to call the public functions in the original plugin files. This will ensure it's much less likely to break things when the plugin gets updated later.


Programatically create a Neo block with children

I figured it out. You have to create a separate block and it somehow figures out it's a child based on the level you specify. So something like this:
[
    'new1' = [
        'modified' => 1,
        'type' => 'parentBlock',
        'enabled' => 1,
        'collapsed' => 0,
        'level' => 0,
        'fields' => [
            'theme' => 'black',
        ],
    ],
    'new2'= [
        'modified' => 1,
        'type' => 'childBlock',
        'enabled' => 1,
        'collapsed' => 0,
        'level' => 1, // increment the level
        'fields' => [
            'value' => 'text',
        ],
    ]
]


Get control panel asset thumbnails into a frontend template

There's actually a really easy way to achieve this (Craft 3 only).

Simply do this in your code:

<img src="{{ image.thumbUrl(int) }}">

{# int is a number that represents the width/height #}

The asset thumbnails are stored in /storage/runtime/assets/thumbs/, so no, they won't be taking up space in your S3 bucket (whereas some local testing inclines me to think that images generated via transforms are stored in your Asset Volume, wherever it's located).


Dynamic Subfolder Paths - folder does not exist even after updating asset directories in settings

Ok, so I have figured out why this wasn't working.
When clicking on reset asset indexes It was always popping up an alert saying that another asset was missing. I already knew this, and it was something I intended on dealing with later. So I clicked OK and as the progress indicator continued to run along with the Tick Icon, I assumed it continued to update everything else, skipping over the error.
But it turns out this isn't the case. The function halts at the error. So once I fixed this other missing asset, everything worked.
It is a little misleading having the progress animation and tick icon still work when in fact nothing is happening.
thanks for all your help. :)


How I add security header on the front-end on Craft CMS

Since you mentioned mod_headers, you can add headers at the web-server level using .htaccess and Apache's header set command: https://httpd.apache.org/docs/2.4/mod/mod_headers.html


Have a look at the Sections and Entries article in the official Craft documentations. It explains how to set up sections and how to configure them to load a particular template if an entry’s URL is requested. https://craftcms.com/docs/sections-and-entries

Another important topic you should get yourself familiar with is how Craft’s routing mechanism works. https://craftcms.com/docs/routing

To configure a template for your homepage you could create a template in craft/templates/index.html and Craft will use it for homepage requests (routing case 4). Or you configure a section in such a way that the homepage’s URI matches one of the section entries’ URIs (routing case 6). Note that there’s also a special checkbox “This is for the homepage” available in the settings for single sections.

With a designated template for your homepage in place, you can now add your slider code snippet to it. In the case that this template is responsible for multiple entries, e.g., entries of a structure section, you could wrap it in a conditional to check against the entry’s ID for example.

{% if entry.id == 12 %}
    <!-- Slider code -->
{% endif %}


Am I correct in thinking that these notifications are being sent via Craft's email settings (currently PHP Mail)?

Probably.  There are plenty of other reasons to not use PHP Mail on a production environment, though.

  If I change Craft's email protocol to GMail, how safe are the credentials I enter and are they encrypted?

If you select the "GMail" as an email delivery method in Craft, Craft sets the SMTP hostname to smtp.gmail.com, forces SMTP authentication over SSL over port 465 and passes in the given username/password.

No encryption is done because SSL is used, so the credentials are as safe as SSL is.


Assign entry id to title with entry form

That would be the same behavior for using {id} in the title format for new entries created in the control panel as well.

The problem with {id} is that's not known until the entry is already saved to the database since it's a database generated number.  That's why it's empty for new entries but re-saving the entry will cause it to appear.

The easiest thing to do would be to generate a unique ID from the template and save it to a custom field on the entry.


Apply shipping without the shipping screen

You can automatically set the shipping method on a cart (e.g. by an ajax call) at any point by POSTing to commerce/cart/updateCart - You just use an input with name shippingMethod and and the value you supply is the handle of your shipping method, e.g. `ground'.

Where you do this is entirely up to you, but note depending how you handle/implement this, changes in the cart contents & addresses can invalidate shipping methods, so you'd typically do this at some point after your cart index page...


How does the Craft CMS built-in web server works?

This just launches PHP's built in web server, documentation for it can be found here: https://www.php.net/manual/en/features.commandline.webserver.php

You can use php -s localhost:8000 instead

You can see available settings by running php -s

Yes you can run multiple versions on different ports

Hope this helps!


Composer require looking to craft/plugins/[plugin] directory but throws runtime error?

I found the real root cause. A internal business plugin which I migrated from Craft 2 to Craft 3 had a composer.json file which required composer/installers and that little bugger was mucking up the whole thing.
So if you find that in your composer.lock file for Craft 3, go in deep and find it!


Solspace Calendar: Export a single event

There's a definitely a syntax error in your first line.

({
    loadOccurrences: false
})

should be:

{
    loadOccurrences: false
}

Also, from their docs, the export method only shows one parameter being passed in and you've specified two.


How to use category in auto generated title?

In the Title Format field, try:

{categoryFieldHandle[0].title}


Loop through entries that share current entry category and restrict to Cat Group Id

You can make use of 'not' to exclude items from your parameters. An example of how this would be implemented in the above use case would be as follows

{% set categories = craft.categories.slug( 'not preferential' ) %}
{% set entries = craft.entries.relatedTo( categories ) %}

If you need to specify category groups or entry sections then use

{% set categories = craft.categories.group( 'groupHandle' ).slug( 'not preferential' ) %}
{% set entries = craft.entries.section( 'sectionHandle' ).relatedTo( categories ) %}


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

I was able to resolve this by testing to see if the pane existed before re-instantiating the element. Happy to consider another answer if someone can explain what is going on better. For now, the following worked:

// Check to see if an element was already registered as a `Craft.Pane`:
if (!$("#myelement.pane").data('pane'))
{
    // Create a pane object if it is not
    this.$pane = new Craft.Pane($("#myelement.pane"));
}
else
{
    // Use the existing pane object if it exists
    this.$pane = $("#myelement.pane").data('pane');
}


Renaming files on Amazon S3 through Craft backend

This is definitely possible in Craft PRO -- I just tested with fine results (latest ver. 2.4.2670). So I would look at your IAM policy. If you have your policy statement scoped to the one bucket in question (and not to all buckets in your account), you could use some wildcard permissions for your main actions, like this, and I think you should be able to rename:

"Action": [
    "s3:Delete*",
    "s3:Get*",
    "s3:List*",
    "s3:Put*"
],

There is no "Update" call into S3 since it is object storage, and any change means a full rewrite of the file.


Where should a plugin create temporary files

PathService has a getTempPath() method which will return the craft/storage/runtime/temp path by default.

Craft uses that for its temporary files and so can plugins.  Just make sure youre plugin is being defensive by giving it a unique filename or create a folder with a unique name and put your files in there, etc.