.htaccess as a Craft template for 301 redirects?

If I understand what you're looking for, it's not so much dangerous as it is not possible. Apache looks at the filesystem and parses the .htaccess file directly, and this is done long before Apache starts to process any PHP.

A route you could take is writing the .htaccess file each time an entry is saved (or having a button that does it so you're not wasting resources). So long as PHP has the write access, this should be doable. Plus, you can still render the file via the template service.

$htaccess = craft()->templates->render('PluginHandle/path/to/template');


/admin/install/ missing resource files (css/js 404) and is unstyled

Most likely an nginx config file issue.  There are some configs that are working for people here: What is the recommended Nginx configuration for Craft?


How do I get the current user’s info over Ajax?

For the redirect I agree, I could not get it too from ajax response, so I just saved it before the ajax call.
var returnUrl = $("input[name='redirect']").val();

Then I can make the redirection :

.success(function(data) {
    if (data.success) {
        window.location.href = returnUrl;
    }

For the user's data could you precise what you want to do?


RAND() is the correct way to do this. (At least, it works in 3.5). One catch is that GraphQL queries are cached by default, so your results will always be returned in the same random order until your cache is invalidated. If you're using Nuxt with a static target, your entries will be displayed in the same order until the cache is expired and your app is regenerated.
Example of a working query:
{
  entries(section: "posts", orderBy:"RAND()") {
    title
    id
  }
}


Cannot find control panel after installation

Web is the public web folder if you followed the recommended install location, so the link to login is just /admin, i.e.

http://your-domain/admin


I get error on live site after Preparse-field update

This was due to version 0.3.0 breaking PHP 5.3 support. A fix has been implemented in 0.3.1 that fixes this.


That's just a quirky byproduct of two subtle features colliding...

Lazy-loading index - You don't immediately see the full list of elements. You'll need to keep scrolling down to reveal them all.

JS-based collapsing - Collapsing/expanding the tree is a client-side behavior. It uses JS to collapse/expand, then stores the current view in a session cookie.

The behavior is simply a minor local issue... it doesn't affect any actual data in your system. The only real solution is to refresh the page when you start seeing the weirdness. Your collapse/expand choices will be remembered, and the items will be reloaded as expected.


How to get a result from search even if the search query contains a part of title?

Like stated in the docs you have to place * around your search term

{% set results = craft.entries({
    search: {
        query: '*sect*',
        subLeft: true,
        subRight: true
    }
}) %}

Note: it would be easier to help you if you show us your query variable


Can I give every structure entry a custom layout by using the same template?

You can setup a dynamic route for /handle/<slug>/followuppage and route the requests to your follow-up page template. From that template you’d have access to a variable called slug that you would then use to query for your structure entry.

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

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


Templating repeatable blocks in a matrix field

It might be worth checking the types of the matrix block like:

{% for block in entry.benefits.all() %}
    {% switch block.type %}
        {% case "intro" %} {# <=== ASSUMING BLOCK TYPE HANDLE #}
            {% for image in block.leadImage.all() %}

            {% endfor %}

{{ block.introTitle }}

{{ block.introParagraph }}

        {% case "details" %} {# <=== ASSUMING BLOCK TYPE HANDLE #}

{{ block.benefit }} - {{ block.description }}

    {% endswitch %}
{% endfor %}

If you're wanting a list inside of a matrix (matrix in a matrix for the Benefits), I'd suggest killing the Benefits block type and adding a SuperTable or Neo field to the Intro block type then you'll be able to list the benefits below each intro in a for loop.


Show on user profile page the commissions he is connected to

You’d need to query for all Matrix Blocks the user is related to using a Matrix Block ElementCriteriaModel. Unfortunatelly this is not possible from the template level by default, you need to either install the plugin Low Blocks, or write some some lines of PHP in a custom plugin.

Here’s how you would have to set the params for the Low Blocks function:

{% set userId = craft.request.lastSegment %}
{% set user = craft.users.id(userId).first() %}

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

{% set matrixField = craft.fields.getFieldByHandle('commissionmembers') %}

{% set blocks = craft.lowblocks.blocks.fieldId(matrixField.id).type('members').relatedTo({
    targetElement: userId,
    field: 'member',
}) %}

{% for block in blocks %}
    {% set commission = block.getOwner() %}

    {{ commission.title }}
    {{ block.function }}
{% endfor %}


How do I access the properties of an object which triggered an event?

Within the context of that event, you will have access to:

$event->params['user']

... which is:

  A UserModel instance representing the user that has just been activated.

Once you've got your user model, you can do something like this:

$event->params['user']->isInGroup('artists')

On a separate note, I believe the correct syntax is:

craft()->on('users.activateUser' ...

You can ditch the "on" in onActivateUser. Check out the official example...


How get entries by sources in a frontend fieldlayout?

UIDs are not yet usable in queries. You would need to extract the UID of the section from the string then fetch the sectionId to use in your query.

Something like this:

{% for tab in entry.fieldLayout.tabs %}
    {{ tab.name }}
    {% for field in tab.getFields() %}
        {{ field.name }}

        {% if field.className == 'craft\\fields\\PlainText' %}
        {# field text settings #}
        {% elseif field.className == 'craft\\fields\\Number' %}
        {# field number settings #}
        {% elseif field.className == 'craft\\fields\\Entries' %}

            {% set sources = [] %}

            {# Start our `entries` query #}
            {% set entries = craft.entries %}

            {# Iterate over sources #}
            {% for source in field.sources %}

                {# If All sources is selected in field definition, skip this #}
                {% if source != '*' %}
                    {# Extract UID from the string #}
                    {% set sectionUid = source | replace({'section:': ''}) %}

                    {# Fetch sectionId from UID and push in `sources` array #}
                    {% set sources = sources | merge([craft.app.sections.getSectionByUid(sectionUid).id]) %}
                {% endif %}
            {% endfor %}

            {# If we have `sources` then add to our query, else, fetch everything #}
            {% set entries = sources ? entries.sectionId(sources) : entries %}
            <select name="fields[{{ field.handle }}][]">
                <option value="">Choose</option>
                {% for entry in entries.all() %}
                    <option value="{{ entry.id }}">{{ entry.title }}</option>
                {% endfor %}
            </select>
        {% endif %}
    {% endfor %}
{% endfor %}

This will cater for multiple sources as well as All being chosen in your field definition


It definitely sounds like whatever mail method you're using isn't configured properly (phpmail or sendmail).  Try swapping to a proper SMTP server and see if that helps or a transactional email provider like Mandrill (https://mandrill.com/) and see if that helps.


Mysql error when defining related tables

Ok, so I figured it out.

The reason it fails to create the tables is because the foreign key has to be of the same type as the primary key it's relating to.

So I just changed:

'quoteId' => AttributeType::String,

to:

'quoteId' => AttributeType::Number,

And it worked!


SproutForms: "an unknown error occurred" in entries template chart

Update: This issue has been fixed in Sprout Forms v2.3.0, which also added Entry Status workflows and support for front-end Entries, Categories, and Tags relations fields ;-)

--

The issue you’re running into with the Sprout Forms chart is due to your PHP version.  We have it on our list and it should be fixed in the next release.  Until we get that release, the way to fix the issue is to upgrade your PHP version to something higher than PHP 5.4


Error when trying to change the database name

MySQL doesn't have a native command for "Rename database" (well, they did at one point, but removed it shortly thereafter), so any MySQL client that offers that functionality ends up writing their own implementation for it.

That is usually somethings as simple as:

Export data and schema to a backup.
Create new database with new name.
Import data and schema from backup.
Delete old database.

But it looks like phpMyAdmin is trying to be more clever than that and failing.  I would try Lindsey's suggestion as a workaround.

Update

Looking at the error, it looks like you've got a dash (-) in your database table name prefix.  That's considered a "special" character by MySQL and must be escaped in backticks `table-prefix.table-name`, which phpMyAdmin doesn't appear to be doing, so it's likely there is a phpMyAdmin bug there, too.


'png_compression_level should be an integer from 0 to 9' upon uploading image

This turned out to be a bug and the fix will be in the next release (current version is 3.5.15.1).


If you just want to add YouTube or Vimeo videos to your page, you'd be better off using a dedicated plugin such as Embedded assets.
It allows you to treat videos as regular assets.


I'm about 99% sure that if you swap from using sendmail to SMTP, or almost any of the other mail transports in the "Mail Adaptors" category in the Craft 3 Plugin Store (SES, Postmark, Mandrill), they won't end up going through proc_open.


How can I get the index of an occurrence in a repeating event on the calendar month view?

If you're referring to the position of the event inside the loop, so you can just use this:

{{ loop.index }}

If you're referring to which occurrence the event is (of the full series of recurrences of that event), then I don't think that is currently possible.


Building a simple search by multiple categories

Building the form is pretty straightforward, you get the categories from your "locations" and "types" category groups using craft.categories
and loop them to build your select options. I choose to pass the category's slug as the value to submit and /results as the URL to submit to.

<form action="{{ url('results') }}" method="get">

    Location
    <select name="location">
        <option value="">all locations</option>
        {% set categories = craft.categories.group('locations') %}
        {% for category in categories %}
            <option value="{{ category.slug }}">{{ category.title }}</option>
        {% endfor %}
    </select>

    Type
    <select name="type">
        <option value="">all types</option>
        {% set categories = craft.categories.group('types') %}
        {% for category in categories %}
            <option value="{{ category.slug }}">{{ category.title }}</option>
        {% endfor %}
    </select>

    <button type="submit">Search</button>

</form>

Getting the entries that are related to categories from both, one or non of your category groups is a little bit more tricky.
In case a category in both select options is selected, you need to use the following syntax for your relatedTo parameter
(see Craft docs: "The relatedTo Param - Passing Multiple Relation Criteria"):

{% set cocktails = craft.entries.section('cocktails').relatedTo('and',
    { sourceElement: currentUser, field: 'favoriteCocktails' },
    { targetElement: gin, field: 'ingredients' }
) %}

I suggest to compose the value for the relatedTo parameter starting with an array ['and'] and then build upon this array,
conditionally adding array elements (relation conditions) using the merge filter.

{# Get the search data #}
{% set locationParam = craft.request.getParam('location') %}
{% set typeParam = craft.request.getParam('type') %}

{# Compose the relation param #}
{% set relationParam = ['and'] %}

{% if locationParam %}
    {% set location = craft.categories.group('locations').slug(locationParam).first() %}
    {% set relationParam = relationParam|merge([{ targetElement: location }]) %}
{% endif %}

{% if typeParam %}
    {% set type = craft.categories.group('types').slug(typeParam).first() %}
    {% set relationParam = relationParam|merge([{ targetElement: type }]) %}
{% endif %}

{# Avoid passing an array with `['and']` only #}
{% if relationParam|length < 2 %}
    {% set relationParam = '' %}
{% endif %}

{# Find and list matching entries #}
{% set entries = craft.entries.relatedTo(relationParam) %}

{% if entries|length %}

        {% for entry in entries %}

{{ entry.title }}

        {% endfor %}

{% else %}
    No entries found.
{% endif %}


Entry URI format with postDate not working

Craft 3 removed the extended DateTime class, so {postDate.year} doesn't work with Craft 3. It must be formatted as {postDate|date('Y')} in the Entry URI format field.


I might be wrong, but your question sounds like you currently don’t even have something set up in the CMS that determines the order the entries should be listed under each category, and the reason for this probably is that you are using a Categories field assigned to the entries’ field layout.

What I am suggesting is to reverse that setup. An Entries field on your category’s field layout not only allows to select which entries you want to relate to each category, but also in which order they should be listed.

Before implementing this you better check if this reversed setup does also make sense for the data entry, but the fact that you’re interested in the sort order is an indication that this might be the case.


JSON response displayed as plain text on submission when creating/editing an entry

I'm guessing you're on MediaTemple?

http://buildwithcraft.com/help/forms-returning-json


How do I have my control panel in English but my site locale to Dutch?

This solutions works for any locale, even if you don't have it installed as a front-end locale.
It also works for Personal or Client Craft installs.

Add a translations file into craft/translations/xx.php named after the currently selected user locale or system locale for
Craft Personal installs and use this code to include any locale's translations you want. You can also customize it
further by overwriting select translations:

<?php
namespace Craft;

if (craft()->request->isCpRequest())
{
    $en = (include '../craft/app/translations/en.php');
    $custom = array(
        'Globals' => 'I freak out!',
    );

    return array_merge($en, $custom);
}

return [];


Adding Categories navigation to show certain entries

If I understand properly, you want to show related FAQ based on categories.
On your entry template, you could do something like this:
{# Fetch the categories of the current entry #}
{% set entryCategories = entry.yourCategoriesFieldHandle.all() %}

{# Find related entries #}
{% set relatedFaqs = craft.entries()
    .section('faqs')
    .relatedTo(entryCategories)
    .all() %}

{# Display related FAQs #}

{% for entry in relatedFaqs %}

{{ entry.title }}

{% endfor %}

Change yourCategoriesFieldHandle to what your field handle is and .section('faqs') to the correct section handle for your FAQ's section.


Accessing disabled matrix blocks in a plugin

Something like this should do it:

$criteria = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->status = null;
$find = $criteria->find();

Setting status to null will return all elements regardless of their status.


Display thumbnail using defineTableAttributes for a custom Element Type

Ok, so I've managed to get an answer to this courtesy of Brandon Kelly.  It's much more simple than I thought.  Firstly, you do not have to specify a relatedTo parameter the defineCriteriaAttributes(). Craft takes care of this automatically.  So in order to retrieve the details of an asset in a table list view you do the following in the getTableAttributeHtml() function in your custom Element Type class:

$relatedAsset = $element->myAssetsField->first();

This simple line of code gets a related myAssetsField of your element. I'm not sure why, but this object is placed in an array...  Maybe someone can tell me why this is the case?

I then took the fist element of the array and used a the getThumbUrl() function which is really handy for quickly outputting the url to a thumbnail.  I passed a size of 60 pixels.

case 'myAttribute>':
{
   if(count($relatedAsset) > 0) {
      return '<img src="'.$relatedAsset[0]->getThumbUrl(60).'">';
   }
   return '';
}

The result is a thumbnail in your table list!
Hope this helps others....


99% of the time when you see this behavior, it's because wherever your server is configured to save PHP's session files to either doesn't exist or isn't writable by PHP.

You can check where that path is by going to yourdomain.com/admin/utils/phpinfo and searching for session.save_path.

If you have the overridePhpSessionLocation config setting set to true, then Craft will set that path to craft/storage/runtime/cache.


Restricting access to user groups with Control Panel access only

I’ve figured out what I was missing. I needed to use can:

{% if currentUser.can('accessCp') ?? false %}

:)


Where/how to add a page title to a section (listing)

What I think you're asking is how to manage content for listing/index page that would pull in entries in a channel. Like the main index page for a blog that shows a list of recent blog entries. Or an "Our Projects" page that's the parent for project detail child pages.

The way I like to do this is create a Single section called "Blog Index" or "Our Projects." You can then use that Blog Index entry to manage the page title or any other content like a hero image or SEO metadata.

Then make sure you check the "Show the Title field" option under it's entry types (where you setup the sections fields).

If you are on the Blog index page, you can use {{ entry.title }} in template.

Or if you are on another page, like a blog entry, and you want to pull the Blog Index title, you can do something like this:

{% set blogIndex = craft.entries.section('blogIndex').one() %}

{{ blogIndex.title }}

I prefer this to using globals because it also handles my settings for the URI route and template instead of relying on file-based template routes.

I think it's possible to pull information about a section/channel/structure like it's name. But the real downside to this approach is it requires the client to change settings in parts of the control panel you don't need or want them poking around in. Those are settings, not content.


What is the optimal place to store CSS files?

In most cases, the best place to store CSS is in a publicly accessible directly, not managed by Craft at all. Such as:

public/assets/css/master.css

Storing your CSS and other front-end assets outside of Craft reduces the overhead of accessing those files. While Craft allows you to store css files in your Craft templates folder, there is additional overhead to access those files as they need to be processed by Craft.


For filtering entries using JS, you could use Isotope JS

First, in your markup give each entry class attribute representing id of category that entry has:

{% for entry in entries %}
{{entry.title}}
{% endfor %}

Then, you will be able to show entries related only to a specific category using JS code like this:

$grid.isotope({ filter: '.category-5' });

..assuming you defined your isotope grid earlier as $grid. In this example, Isotope will show all entries related to the category with id 5.


Change title url of elementtype in the list

I found the solution of this was under my nose,

I added this

public function populateElementModel($row){

  $model = Plugin_ClientModel::populateModel($row);
  return $model;

}

In Plugin_ClientElementType and then getCpEditUrl() it works.


How to prevent access to asset folder (and redirect to other page)?

It would be much safer and easier to work with if you put all assets folders into domain.com/assets/ as it can cause such conflicts.


How to show events for "This Weekend, Next Week"

Twigs date_modify filter accepts every string, which is supported by phps strtotime().

These strings are called Relative Formats.

.

Examples:

In the original post you used:

{% set day = date('m/d/Y') %}
{% set nextDay = day|date_modify('+1 day') %}

but with Relative Formats you can also do something like this:

{% set var = day|date_modify('now') %}
{% set var = day|date_modify('10 September 2000') %}
{% set var = day|date_modify('+1 week') %}
{% set var = day|date_modify('+1 week 2 days 4 hours 2 seconds') %}
{% set var = day|date_modify('next Thursday') %}
{% set var = day|date_modify('last Monday') %}
{% set var = day|date_modify('next month') %}

(These are equivalents of the php-doc examples )

.

So this weekend would be:

{% set var = day|date_modify('next Friday') %}

Or Saturday, personally I start my weekends on Thursday, so it's hard to give a good example ;)

Next weekend:

{% set var = day|date_modify('next Friday +7 days') %}

Next weekend in one year, half an hour ago:

{% set var = day|date_modify('next Friday +1 year -30 minutes') %}


Solved this by

creating the Set Password form in a template with the correct
return
setting it's path with setPasswordPath
setting a path for    setPasswordSuccessPath to catch forgot password
resets


Trouble with merging Numbers in an Advanced Search

Rename the field handle to something else, depth is a deprecated attribute for ElementCriteriaModel.


500 Error after Dreamhost server upgrade

Dreamhost was ...uh...less than helpful on the matter.

That's always been my experience with them.
Best I can tell (from https://github.com/the-paperless-project/paperless/issues/98 which has a similar error message) that error is coming from Imagick.
Whether it's a bug in Imagick (possible) or Dreamhost has misconfigured it on the VPS (more likely), it's hard to say, but either way, they should be looking into it.


I managed to figure this out by looking through a few other posts:

Advanced Search
Building a simple search by multiple categories
Building Results From Advanced Search Form
How to filter entries by clicking multiple categories on front end
Fetching entries from an advanced search form on the front end

Which I then took their knowledge and put together my own form and results template. With the results I wanted the same code & template to be used for search results AND the general "knowledge" page.

Filter Form

<form action="{{ url('knowledge') }}">

        {% set categoryEntries = craft.entries.limit(null) %}

        {% for category in craft.categories.group('knowledge') %}

            {% set categoriesEntryCount = categoryEntries.relatedTo(category).total() %}

              <input type="checkbox" name="category[]" value="{{ category.slug }}" id="{{ category.slug }}">
              {{ category.title }} ({{ categoriesEntryCount }})

        {% endfor %}

</form>

Results

    {% set parameters =
        {
            section: 'channelKnowledge',
            limit: '1'
        }
    %}

    {% set categoryQuery = craft.request.getParam('category') %}

    {% if categoryQuery %}
        {% set categoryQueryCategories = craft.categories.group('knowledge').slug(categoryQuery) %}
        {% set entries = craft.entries(parameters).relatedTo(categoryQueryCategories).order('score') %}
    {% else %}
        {% set entries = craft.entries(parameters) %}
    {% endif %}

    {% paginate entries as channelKnowledgeEntries %}

    {% if entries|length %}

        {% for entry in channelKnowledgeEntries %}

            {{ entry.title }}

        {% endfor %}

    {% else %}

No Results

    {% endif %}

    {% if paginate %}

            {% if paginate.prevUrl %}

                    Previous

            {% endif %}

                {% for page, url in paginate.getPrevUrls(5) %}

                        {{ page }}

                {% endfor %}

                        {{ paginate.currentPage }}

                {% for page, url in paginate.getNextUrls(5) %}

                        {{ page }}

                {% endfor %}

            {% if paginate.nextUrl %}

                    Next

            {% endif %}

    {% endif %}

{% endpaginate %}


Cloudinary thumbnail creation for assets

You can catch the EVENT_GET_ASSET_THUMB_URL event in your plugin and return the $event->url:

   Event::on(Assets::class, Assets::EVENT_GET_ASSET_THUMB_URL, function(GetAssetThumbUrlEvent $event) {
            $event->url = $this->thumbUrl($event);
        });

   protected function thumbUrl($event)
      {
           return "{$this->cloudinary_ulr}/image/upload/w_{$event->width},h_{$event->height}/{$event->asset->filename}";
      }


If I had to guess, they made a chance in MySQL 5.7 that's breaking Craft and you've found a bug.  We haven't done any 5.7 testing, since it's not officially released, yet, but I'll install it and do some verification and update this answer.

Update:

This was a bug in Craft when using MySQL 5.7 and has been fixed for the next (post 2.2.2588) release.


What's the best way to increment a number of a class or id?

By using the default filter you can get away with a single line of Twig to set and increment the counter:

{% for block in entry.news %}
    {% if block.type == "bodyBlock" %}
        {{ block.body }}
    {% elseif block.type == "codeBlock" %}
        {% set counter = ( counter | default(0) ) + 1 %}

            ...

    {% endif %}
{% endfor %}

Also, I'm guessing you need the accordion elements to be chronologically numbered, but if you don't, you can use the index property of the loop variable, which is available inside the for loop:

{% for block in entry.news %}
    {% if block.type == "bodyBlock" %}
        {{ block.body }}
    {% elseif block.type == "codeBlock" %}

            ...

    {% endif %}
{% endfor %}


You can’t use this special Twig function to get reverse related entries at all, as you’re not dealing with reverse relations in that context.

From a stageEvent entry you can just loop through the Super Table rows and get the related artist entry like so:

{% for row in entry.lineUp %}
    {% set artistPerforming = row.artistPerforming.first() %}

    {% if artistPerforming %}
        {{ artistPerforming.title }}
    {% endif %}
{% endfor %}


So, thanks to @carlcs for verifying it was my setup…

turns out I had set the asset's Default Upload Location to include the slug (i.e. /photography/{slug}) and restricted uploads to that folder. This way images would end up in a folder whose name matched the entry slug, making it easier to clean out unused assets from time-to-time.

But that approach was the source of the problem. Once I removed {slug} from the default upload location it all worked as expected, the caption field appeared immediately after adding the asset.

Of course, in retrospect this makes total sense — there's no {slug} until you save the entry.


To add a row at every 4th item, you can use twig's batch filter:

Twig Batch

Alternatively(a little more hacky) you can do {% if loop.index is divisible by(4) %} stuff {% endif %}. But batch is probably better.


Why two equal variables give false statement?

It seems like you're trying to compare two EntryModel objects. Could you just compare their ids?

{% if rowParent.id == parent.id %}
    // Go
{% endif %}

Also, try using Twig's dump() function to find out exactly what's in those variables/objects.

<pre>
    {{ dump(parent) }}
</pre>

I believe you'll have to have devMode enabled to use dump().


Where to enter URL for Live Preview in Craft 3?

The "Entry URI Format" in Section settings is used for Live Preview by default. If you add additional "Preview Targets," then the Entry URI Format will show up as "Primary entry page" in the list of Live Preview options.

Preview Targets are "additional" because they aren't required and not used for template routing, unlike the "Entry URI Format" above it. They're only used for Live Preview mode.

The Craft docs on Preview Targets use the example of a blog post that you want to preview how it will look as an excerpt on the homepage or in a listing page like the blog index in addition to its main entry page.


How to show details on linked entry in CP (another field inside related entry)

Basically, what you want to do isn't possible – there's no hook for modifying the content in a relational field's input HTML.

The getEntryTableAttributeHtml hook is meant for element indexes (such as the entry list displayed at /admin/settings/entries), not relational fields (such as Entries, which is what you're using in your SuperTable).

The easiest workaround would be to add the value of the ingredientMeasure field to your ingredient entries' title format.

First, you'll need to create a new custom field for your entries' titles – the handle title is reserved, so call it ingredientTitle or the like, and add it to your "Ingredients" section's entry type. Make the field required. Second, you'll need to go into your "Ingredients" section's entry type settings, and uncheck the "Show the Title field" checkbox. Then, add something like this to "Title format" field:

{ingredientTitle} ({ingredientMeasure})

Finally – you'll need to re-save all your ingredient entries in order to have their titles updated to the new format.

Obviously, the big tradeoff with this method is that your ingredient won't actually be titled "Spinach" anymore – it'll be titled something like "Spinach (100g)". In your templates, this can easily be remedied by using

<h1>{{ entry.ingredientTitle }}</h1>

Instead of the normal entry.title, wherever appropriate.

Also, unless you want the ingredientsMeasure field to be part of the Ingredient entries' slugs, you should replace {slug} in your Ingredients Section's URL format with {ingredientsTitle|kebab}.


Yes, {{url('handle')}} will output the correct URL for whichever localization your user is currently in. Be sure to adjust your siteUrl configuration in your app/config/general.php file. Depending on your set up, it can look something like this:

return array(
    'siteUrl' => array(
        'en' => 'http://mysite.com/en',
        'fr' => 'http://mysite.com/fr'
    )
);

For more information, check out Step 4 in the Localization Guide.


You need to check the currentUser country if it's the same as the option value -> select the option

<option {{ currentUser.country.value == option.value? 'selected' : '' }} value="{{ option.value }}" >{{ option.label }}</option>


Why does Craft set no-cache headers for all requests?

Craft doesn't explicitly set any caching headers in the response, but you can control exactly how you want your caching headers to behave from your templates with the {% header %} tag.

For example:

{# Tell the browser to cache this page for 30 days #}
{% set expiry = now|date_modify('+30 days') %}

{% header "Cache-Control: max-age=" ~ expiry.timestamp %}
{% header "Pragma: cache" %}
{% header "Expires: " ~ expiry|date('D, d M Y H:i:s', 'GMT') ~ " GMT" %}

By default PHP has the session_cache_limiter() method set to nocache, which is probably what you're seeing.


Can the “Commerce Products”-field allow for selection of variants?

At the moment there is no Commerce variants field type unfortunately.   It comes up a lot, someone should post it here: https://github.com/craftcms/commerce/issues.

Edit - I've gone ahead and posted this here - https://github.com/craftcms/commerce/issues

In the meantime yes a text or eg table field could store variant IDs...which I suppose is ultimately what a proper field type would do basically.


I've just realised I can do this:

{% set params = { section : 'stories', order : 'postDate desc', relatedTo: category, limit : '4', storyImage: ':notempty:' } %}

Where "storyImage" is the field name of my image field


Can entries be disabled by default for 2/3 of the languages on my website

Is it possible to have the Japanese and English version disabled by default?

Yes. Visit Settings -> Sections -> [Your Section Name] inside the Control Panel.

Under the heading Which locales should entries in this section target? there's a Default Entry Status Lightswitch for each locale. Make sure the Lightswitches are off (i.e., not green) for the English and Japanese locales, and you're all set.

Obviously, you'll need to do this for any and all sections targeting the 3 locales – there's no "global" setting for it.


Not really (or not without a custom solution anyway) — tags are designed to be added by anyone. You might be better off using categories for this, which you can resist access to via userGroup permissions.


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

Maybe The purchase Patterns Plugin Could Solve your problem.
https://github.com/ethercreative/purchase-patterns/blob/v1/README.md


Field removed from entry layout is still displaying

I figured it out. The problem was that the code that set seoAuthor on every template was still there. So even tho the field was removed from the layout, the db still contains that field, so is able to retrieve it.

The fix was to remove the code that set the variable in the templates, and now works as intended.

One thing that still confuses me is why craft still pulls the data if is not in the layout anymore.


Module's control panel sub-navigation is not working properly

This is working for me.
Module.php
        Event::on(Cp::class, Cp::EVENT_REGISTER_CP_NAV_ITEMS, function (RegisterCpNavItemsEvent $event) {
            $event->navItems[] = [
                'url' => 'modules/video',
                'label' => 'Video-Converter',
                'icon' => '@modules/icon-mask.svg',

                'subnav' => [
                    'inhex' => [
                        'url' => 'modules/video/index',
                        'label' => 'Project-Video',
                    ],
                    'old' => [
                        'url' => 'modules/video/old',
                        'label' => 'Old Projects',
                    ],
                ]
            ];
        });

And in the templates I am using e.g.
{% extends '_layouts/cp' %}

{% set title = 'Old Projects' %}
{% set selectedSubnavItem = 'old' %}


You can, just by naming the file with a .css extension, and then accessing it just like any other template in there. For example, you could have the file craft/templates/styles/styles.css, and that would be accessible from http://example.com/styles/styles.css. Craft will even serve it with a text/css Content-Type header.

However, this is only a good idea in certain situations. Directly loading your CSS by pointing the URL to a publicly-accessible file that Apache can serve without PHP/Craft’s help is going to be much less work for your server (serving static files is what Apache does best). Also, browsers won’t be able to cache those dynamic CSS requests (unless you manually override the cache headers from your template using the {% header %} tag, but then, there would be no point in having it dynamically generated in the first place). So this will have some impact on your overall page load times.

You’d probably be better off just generating your CSS styles that have to be dynamic  right in the main HTML templates within <style> tags, or using the {% includeCss %} tag.


Manually creating Security Key gives PHP error

Well then. Apparently my shell user was using a different version of php than my domain. I was still at 5.6 on my shell user. I was all sorts of confused because I had a phpinfo.php file setup at my domain showing PHP 7.0, and in the web hosting domain panel, I had 7.0 chosen. Finally wrote to support and they sent directions on how to change it. Once I updated that, the security key was created just fine.


Twig doesn't accept || or &&... Try using or and and instead.

{% if foo == 'x' or foo == 'y' %}

Important to note, they must be lowercase.

You may also want to take a look at this question, which shows another way to write a similar condition:

{% if foo in ['x', 'y'] %}


Populate or change the selection options in one field based on selected option in another field in the CP

I would write a custom fieldtype (http://buildwithcraft.com/docs/plugins/field-types) with two selects. Makes sense to make it as one field if they are dependent of eachother.

Just store the field as json (AttributeType::Mixed) and inject your own javascript in the fields getFieldHtml()


I had to run sudo php5enmod mcrypt to enable the module.

It seems this has changed between 12.04 and 14.04—in 12.04 it was enabled automatically.


4 Different HTML from single Craft 3 CMS on 4 different domains?

Yes, you can. How you organize the templates for each site is completely up to you. Here's the docs on setting up multiple sites in Craft.

I would likely use a different layout template for each site. So when I extended at the top of an individual page template it would look like this.

{% extends "layouts/_site_one" %}

Or like this

{% extends "layouts/_site_two" %}


Commerce (as at V2) has basic stock handling that will do exactly what you mention - for each product you can set a stock level (alternatively, you can set it to unlimited stock if you wish).  When orders are completed stock is debited by the amount sold (note stock is not debited when items are added to carts - which is good, because it means you don't have to deal with not being able to sell things that are locked up in stale carts).

Commerce will not let you sell out of stock items, and there are template tests you can use to display the stock state in any way you choose (be careful with caching in this area!).

Note that the stock handling is fairly simplistic - e.g. I am pretty sure that there is no automatic return handling (so if you e.g. cancel/refund an order, it won't automatically add the stock back).

If you need stock handling beyond this then you would need to look at building a plugin specific for you needs (or one that integrates a sophisticated inventory handling system).


Mark a Commerce Order as Paid, via a custom plugin

Your best bet would be to create a transaction for the full amount:

$transaction = Plugin::getInstance()->transactions->createTransaction($order);
$transaction->status = \craft\commerce\records\Transaction::STATUS_SUCCESS;
$transaction->type = \craft\commerce\records\Transaction::TYPE_PURCHASE;
Plugin::getInstance()->transactions->saveTransaction($transaction);
$order->updateOrderPaidTotal();


Re-using includes when the object type changes (entry vs block) - what is the best method?

From what I can see here, the only important object you care about in the include file is the video object. So what you could do is simply passing the video field in parameter directly, using, for the entry:

{% include '_includes/matrix/video' with { video : entry.video } only %}

...and for the matrix block:

{% include '_includes/matrix/video' with { video : block.video } only %}

But then you would need to explicitly call each matrix block type with associated parameters.

I would in any case add the "only" keyword after the parameters, as it guarantees that your template will be isolated from other variables already defined in the main template.


How to create a CMS editable channel section index page?

Create a Single called "Blog Overview" and set its URI to "blog" and its "Entry Template" to "blog/index" (your blog listing template).

Then just override the title to "Blog" either by hard coding it in the index template, using an "title override" field, not showing its title etc.


Multiple regexes/masks in Sprout Field validation

Currently, Sprout Fields Phone Field only supports a single mask.

If you need more advanced pattern support, a Regex Field Type is probably the way to go.

Here is one that came up in my search:

mn_matchinput


Ignoring customAsciiCharMappings for the moment, Craft uses Stringy for this type of thing.

The have some special logic for German and Bulgarian character replacements and it looks like those particular characters will only get replaced if the locale of the site you're currently editing is bg: https://github.com/danielstjules/Stringy/blob/master/src/Stringy.php#L1874-L1877


How to make field instructions show as tooltip?

Install control panel CSS plugin, and add the following style.
.field .heading{
  position: relative;
}

.field.tooltip-icon-append label:after{
    content: "i";
    font-style: italic;
    font-family: open-sans;
    display: inline-block;
    position: relative!important;
    top: 0!important;
    left: 0!important;
    color: #fff;
    width: 17px;
    height: 17px;
    margin-top: 0;
    margin-left: 5px!important;
    line-height: 17px;
    font-size: 13px;
    background-color: rgba(0,135,255,.7);
    border-radius: 50%;
    text-align: center;
    opacity: 1;
    -webkit-font-smoothing: auto;
}

.field .heading .instructions {
    visibility: hidden;
    max-width: 100vw;
    background-color: #ddd;
    color: #000;
    border-radius: 6px;
    padding: 10px;
    position: absolute;
    z-index: 1000;
    bottom: 150%;
    width: 300px;
    opacity: 0;
    box-shadow: 0 0 0 1px rgba(205,216,228,.25), 0 2px 12px rgba(205,216,228,.5);
    transition: opacity .3s;
}

.field .instructions::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 25px;
    border-width: 10px;
    border-style: solid;
    border-color: #ddd transparent transparent;
}

.field .heading:hover .instructions {
  visibility: visible;
  opacity: 1;
}

Install control panel JS plugin and add the following code.
    $(".field>.heading").each(function(){
        var instruction = $(this).find(".instructions");
        if(instruction.length !== 0){
            $(this).parent().addClass("tooltip-icon-append");
        }
    });


They don't need to clash per se, but it depends on the way you build your project structure. I'm front-end focussed, so my setup is like:

    projectfolder
      src
      public

public

(you could also call this 'craft' or 'dist' or another name to indicate this is the final product) This is where Craft is installed with the craft installer. So nothing Craft related will be outside that folder and therefor should not crash with the vue installer.

src

Src countains all front-end source files, like es6 javascript files, Scss files, static assets, fonts etc. I use webpack to transpile these to a folder inside public\web, so the destination files will always be inside public\web and therefore available for use in templates.

using the vue installer?

The vue installer is probably mostly/only focussed on projects where you only use front end. But apart from that; it has it's own project structure you probably can't change. You might be able to find a way to use the installer and make the created structure work with Craft, but you still need other tools, like webpack, to make it work without having all front end sources inside the folders created with the craft installer.

So my advise

is leave that installer and learn how to create your own structure. That way you are way more flexible, don't need to use their rules and can leave things behind you don't need and add your own config. In the end you will install more front-end tools and configuration files for linters, transpilers etc. anyway and you can't do that with the vue installer alone. So just create your own setup with all your configs and use that for every new project would be my advise.


Errors after Upgrading from 3.0.35 > 3.041

The easiest way is to make sure you have Composer installed.

Then you can go to your project's root and run composer update to pull in a fresh set of dependencies.


According to this page, this is how it's done:

{% set entries = craft.entries.search('interest:interestSearchValue destination:destinationSearchValue) %}

So, using the posted variables:

{% set entries = craft.entries.search('interest:' ~ craft.request.param('interest') ~ ' destination:' ~ craft.request.param('destination')) %}


Category slug is getting numbers appended to it

When you save an entry/category that is supposed to have its own URL, Craft will assign it a unique URI, based on the section/category group’s URL Format setting.

For example, let’s say you have a section called News, and its “Entries in this section have their own URLs” checkbox is checked, and it has this URL Format:

news/{slug}

When you save a News entry, Craft will assign it a unique URI based on that URL Format. If the entry’s slug is “foo”, then the first URI Craft will try to assign it will be “news/foo”.

However, if that URI is already taken by another entry/category (or some third party element type), Craft will increment the slug and try again:

news/foo-1
news/foo-2
news/foo-3
etc.

(If incrementing the slug has no effect on the URI – because the URL Format doesn’t actually contain a {slug} token – then Craft will simply give up and add a validation error to the element.)

Once it has found a URI that is actually unique, it will update the element’s Slug with the incremented version.

So in your case, when you save a category with the slug “australia” and it becomes “australia-6“, that means that you have 6 other elements that had been saved with the slug “australia” before it, with the same URL Format that your current category has, and so “australia-6” was just the first slug Craft could find that resulted in your category having a unique URI.

To find out which elements your category’s URI is conflicting with, you can go to Entries > All Entries, and search for slug:australia, and click through each of your category groups in the Categories tab, searching for slug:australia in each of them.


Using Services to get all the Categories related to an Entry?

If you have an EntryModel and know the category field's handle, you don't really need a service:

$categories = $entry->categoryFieldHandle;

In other cases, you can construct an ElementCriteriaModel to search for related elements (categories, entries, users or assets), using a number of different variables. Easy example to get related categories from an entry ID:

$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->relatedTo = array($entryId);
$categories = craft()->elements->findElements($criteria);


There's currently no way to achieve this with Feed Me. A single feed would represent a collection of items to be imported as elements/entries.

One method your could consider is setting up a feed for a single entry, then use the optional url parameter when calling it via the direct feed URL. This overrides the URL used in your feed settings with the one you provide.

This is described https://verbb.io/craft-plugins/feed-me/docs/feature-tour/trigger-import-via-cron


Querying channel entries hits memory limit

Assuming you're referring to Craft 2, the EntryModels that get returned to a template do have a significant memory overhead attached to them you're probably running into.  Doing the math, even bumping your php.ini memory_limit up to 256M is only going to get your around 260 results coming back with your given fields/configuration.

It's one of the big things we first improved in the upcoming Craft 3.

In the meantime, you've got a couple of options:

Paginate the results so you can do them in smaller batches.
AJAX/lazy load the results over multiple requests in smaller batches.
Write a plugin (https://craftcms.com/docs/plugins) that bypasses Craft's Element/Model loading and queries the database directly and returns only the data you explicitly need back to the template, without all of the model overheard.


Your entry.expiration is actually an object of type DateTime thus you'll have the full power of PHPs DateDiff functionality

$interval = $datetime1->diff($datetime2);

In Twig this is something like

{% set difference = now.diff(entry.expiration) %}
{{ difference.format('%R%a days') }}

now should be the current date


Can Craft be used on same site as other eCommerce Solutions

You shouldn't have any issues running multiple applications on the same host but it would be smarter to decouple the different applications and build a bridge between them.

I've never worked with OSCommerce or OpenCart so I can't speak to the specifics of what's involved in doing that but if your high-level goal is to run Craft on the same server as the other application(s), that should be fine.


Is it possible to have different fields associated with users in different groups?

Currently, this is not possible in Craft via the the Control Panel.

If you are managing user profiles from the front-end, you can manage different fields for different user groups manually.

A few considerations:

You can't set a field to required in Craft if it will be optional for one of the user groups on the front-end and not the other.  You may have to manage required fields in another way.
An admin with direct access to Users in the CP will have no signal in the UI as to which fields belong to which User Groups.


Loop over table field in Element API plugin

A table field contains a simple array, you can serialize and unserialize it as it is. So there is no custom action required by your side.
Just use it in PHP like every other textual field


Display entries which share tags (2 or more)

After chatting on Discord a bit more, here's a solution in case it helps somebody:

{# Base query #}
{% set baseQuery = craft
    .entries
    .section('stories')
    .orderBy('RAND()')
    .with(['storyKeywords']) %}

{# Fetch one story at random #}
{% set baseStory = baseQuery.one() %}

Base random story: {{ baseStory.title }}

{# Fetch a second story related to `baseStory` at random #}
{% set relatedStory = clone(baseQuery)
    .relatedTo({
        targetElement: baseStory.storyKeywords,
        field: 'storyKeywords'
    })
    .id('not ' ~ baseStory.id)
    .one() %}

Related Story: {{ relatedStory.title }}

{% set baseKeywords = baseStory.storyKeywords %}
{% set relatedKeywords = relatedStory.storyKeywords %}

All tags in common: {{ baseKeywords | filter((tag) => tag.title in relatedKeywords) | join(', ') }}

Number of tags in common: {{ baseKeywords | filter((tag) => tag.title in relatedKeywords) | length }}


I wouldn't normally set up a site like this — but given your setup, the following should work.

In the category settings, make sure that your category has 'Entries in this section have their own URLs' checked.
Set your category url format to:

top-level: {slug}
nested categories: {parent.uri}/{slug}

Set your article entry url format in the channel settings to {category.last.uri}/{slug} (where 'category' is the handle of your category field.)

Note the use of last. Categories will be returned as an Element Criteria Model which behaves much like an array (even if there is only one defined). The use of last will return the last category element, which should be the uri pattern that you're looking for.

Of course, if you have other routes in the CMS you will have to be careful about routing conflicts.

As a side note, you might want to consider using a 'structure' instead of 'categories'. I commonly use a single structure that represents all of the top level pages in a site, using Entry Types to distinguish the various field requirements and page layouts. You can then include the appropriate template layout automatically based on 'entry.type'. Likewise, you can use this structure to easily generate your site nav, and be fairly confident you won't run into any routing conflicts. The only reason I mention this is that you seem to already be heading in this direction with your current setup.

Edit: I might also add that you will want to make your category field required, otherwise there will be no route to the article in question.


I think that's just the way they have set up the templates in the example, so what you're doing is just fine (using {% block %}), if that's how your templates are set up.

The difference is by using {% set %} you are just setting your content to a variable which would be {{ echoed }} into the layout file that you extend. Whereas using {% block %} you are telling twig what block of content should be inherited into the layout you are extending.

The twig docs probably explain it better:

http://twig.sensiolabs.org/doc/tags/extends.html
http://twig.sensiolabs.org/doc/tags/set.html

From the looks of it with the plugin in question, providing you add {{ craft.sproutSeo.optimize() }} into your layout template you should be all good to go.

Example with {% set %}

_layout.html

<body>
  {{ content }}
</body>

index.html

{% extends '_layout' %}

{% set content %}
 Some content
{% endset %}

Example with {% block %}

_layout.html

<body>
  {% block content %}{% endblock %}
</body>

index.html

{% extends '_layout' %}

{% block content %}
 Some content
{% endblock %}


What would cause a user's activation link to fail?

They could already be active Users
Their activation link could have timed out

1) happens more often than I'd think, people try using it as a way of "getting to the site again"

2) Can be controlled in /config/general.php - https://craftcms.com/docs/config-settings#verificationCodeDuration


To group by the first letter you would simply use the slice filter within Craft's group
filter.

For all non letter characters you can now use Craft's replace filter (it does regex since Craft 2.2)
and replace them with whatever you want these entries to be sorted by.

{% set entriesGrouped = entries|group('title|slice(0, 1)|upper|replace("/[^A-Z]/", "0-9")') %}

{% for letter, entriesInGroup in entriesGrouped %}
    {{ letter }}
    {% for entry in entriesInGroup %}
        {{ entry.title }}
    {% endfor %}
{% endfor %}


Query Entries based on current Entry's related Entries

You're close!

In your entry query, change .relatedMarkets([allMarkets]) to .relatedTo(allMarkets) (use relatedTo instead and you don't need array brackets).

Final code looks like:

{% set allMarkets = entry.relatedMarkets.all() %}
{% set currentID = entry.id %}

{% set expertBlog = craft.entries()
    .section('blog')
    .orderBy('postDate desc')
    .expertOpinion(true)
    .relatedTo(allMarkets)
    .id(['not', currentID])
    .limit(3)
%}


I'm going to attempt to answer my own question now that I have had the issue resolved. Clearly this is a local server environmental issue. The explanation I have received from the hosting provider is not one I understand too well, but here it is for the record.

  For security reasons, the PHP FPM process on your server executes
  scripts in a separate chroot(2) environment, meaning that only a
  limited set of resources are available at runtime.  This sometimes
  causes problems when the chrooted program requires resources that
  don't exist outside the chroot environment that are loaded during
  runtime rather than being built in to the binary, or dynamically
  linked before the system chroot call.  The iconv extension has this
  problem, in loading .so binary data files corresponding to the
  encodings it's manipulating.  On your server, the files it loads were
  in /usr/lib/x86_64-linux-gnu/gconv, and had not been copied into the
  chroot environment at /srv/php-fpm/rdc.  Copying the contents of
  /usr/lib/x86_64-linux-gnu/gconv to
  /srv/php-fpm/rdc/usr/lib/x86_64-linux-gnu/gconv has fixed the issue.


Adding 301 permanent redirections in Craft CMS

Not sure how you're trying to do the redirect, but the common ways in Craft are:

1) From .htaccess if you're using Apache: https://httpd.apache.org/docs/2.4/rewrite/remapping.html

2) Using a plugin that lets you set up redirects from the Craft control panel: https://plugins.craftcms.com/search?q=redirect


Filter entry query by a custom field value

Your code should work. Make sure that your Settings → Fields → Navigation has Use this field’s values as search keywords checked.
Once you're sure it is checked, run ./craft resave/entries --update-search-index and it should start working.
Note that instead of searching, you could use:
{% set nav = craft.entries()
    .section('pages')
    .navigation('mainNavigation')
    .all() %}


How can you return elements between two values?

You’re close! You just need to begin the array with "and":

$criteria = craft()->elements->getCriteria(ElementType::User);
$criteria->customNumberField = array('and', '>=5', '<=10');

$users = $criteria->find();

This same thing could also be accomplished from your templates like this:

{% set users = craft.users.customNumberField('and', '>=5', '<=10') %}


New user validates without confirming email

Since you're bypassing Craft's own UsersController->actionSaveUser(), you'll need to replicate a bit more of its functionality in order for it to work like you're wanting.

First you'll want to make sure that "Require Email Verification" is checked under Settings->Users->Settings in the control panel.

Then your UserModel will also need to set a few more things:

$user->unverifiedEmail = $email;
$user->pending = true;

Completely untested, but that should do it.

I highly recommend looking over Craft's default actionSaveUser implementation as there are many permissions/security guards in place for public registration that you should probably consider as well.


Your best bet would be to find a database backup that has the order information that was deleted and write a script that re-inserts that order info into your existing database.


Validate a lineItem option within a plugin?

I've achieved something similar but used commerce_lineItems.onBeforeSaveLineItem.

This event is fired every time a line item is created or edited. Fired on /updateCart (product page) or /updateLineItem (cart page).

You might run into problems because the lineItems in the event won't contain a post request unless its the lineItem that triggered the event through a form.

You need to grab the events line item and check it against the lineItemId in the post request before doing any comparisons - unless its a new lineItem.

// Get the line item being saved from the event
$item = $event->params['lineItem'];

// Is this a new line item?
$isNewLineItem = $event->params['isNewLineItem'];

// Get the line item id that triggered the save from the post request
// (this will only exist if we're updated a line item that currently exists)
$lineItemId = craft()->request->getPost( 'lineItemId' );

// If the current line item being saved is new
// OR
// If its an existing line item and matches the one that triggered the event
if ( $isNewLineItem || $item->id == $lineItemId ) {
  //rest of the code
}

I then looked to see if the option was in the post request.

$text = craft()->request->getPost( 'options.Text' );

If it wasn't I added a flash message and stopped the action.

$event->performAction = false;
craft()->userSession->setFlash( "itemError", "You must add some text before adding this product to your basket" );


Limiting entries object when using as json_encode

As per the docs:

Element queries are specialized query builders under the hood, so they
support most of the same methods provided by craft\db\Query.

...So, in your case you could use select() to only select the fields you want:
{% set services = craft.entries.section('services').asArray().select(['title','id','url']).all() %}


Allow users to edit user account email from front end form in Craft 3?

UsersController::actionStartElevatedSession() is public so you can access it via frontend form but you should only call it via ajax request.

You can just submit your normal user form via ajax and if it contains an error with key currentPassword you can be sure to require a elevated session and display a password form to enter it in order to create a request to the route above. This will start the session and you can submit the user form a second time.

So in summary: you don't need a custom controller at all. You can change the user's email and password by submitting a form with newPassword and email but you'll receive the error Incorrect current password if there is no elevated session or if the password parameter doesn't match the user's old password (you always need to submit it together).

If you want additional security you can send the sendVerificationEmail to force users to verify their email by sending them a mail. But keep in mind all those things can be manipulated via frontend request. Users are totally free to change the html of your form


Is there any way of distinguishing whether a Date field's "time" is set or not?

The values entered in Date/Time fields are always saved as Craft datetime objects. This means it doesn't matter if you configure it to show the date, the time or both, Craft always saves them the same.

If you make it to show both, so you're able to enter a time for your events, you have to do this in the field's settings for all entries of your "Event" entry type. So to be able to switch input forms (a truly "optional" time field), you would actually need to have two entry types "Event with date" and "Event without date". Not the cleanest solution in my opinion.

What I'd do instead is to use two separate Date/Time fields, one configured to show the date and the other one to show the time. The client would only fill out the time field when necessary. And in the template you'd be able to check for an empty field.

{{ entry.eventDate|date('l, j. F Y') }}

{% if entry.eventTime %}
    {{ entry.eventTime|date('G:i') }}
{% endif %}


Just to add; we are apparently seeing this issue too. Or to be more clear: we haven't seen it ourselves, but our client keeps getting reports from their customers that Activation links are not working - giving "error messages" when clicked. We've then had the trouble mail forwarded to us, we've clicked the link, and it's been fine.

Looks like there is some mail client out there mangling the activation links. Which is bad. And we don't know of a solution.

The codes are not expired.


Automated deployment with content migrations and structural changes

Something I wish I knew a long time ago, as it has bitten us quite a few times already in the past. Nothing as bad as having an automated deployment process that fails once in a while.
I'm sharing it here, but I believe it would be good to add it to the knowledge base too (https://craftcms.com/knowledge-base/deployment-best-practices)
The solution is to split up the structural migration and the content migration.
Pull the update for git and then run
craft update/composer-install --interactive=0
craft migrate/all --no-content --interactive=0
craft project-config/apply --force
craft migrate --track=content --interactive=0

Pretty straightforward and simple, but I was not aware of the --no-content flag until recently as it not in the command help.  I hope it will help somebody in the future!
(The --interactive=0 and --force flags are there because it is an unattended deploy)


The Composer "Killed" error messages usually means Composer ran out of memory.
https://github.com/composer/composer/issues/1815
Either your on a VM with limited resources or your php.ini file has a low memory_limit set.
Increasing the memory, in either case, should resolve it.


302 redirects to locales in main index.php

I would suggest making the “admin” check a little more strict:

// Make sure this isn't a CP request
if (!isset($_GET['p']) || strncmp($_GET['p'], 'admin', 5) !== 0)
{
    // ...

(Assuming you’re using the recommended .htaccess redirect rule, by the time the request hits index.php, the original request URI will be available as $_GET['p'].)

The Accept-Language header can actually include multiple languages, so you might want to consider looking at all of them, sorted by weight. HttpRequestService::getBrowserLanguages() has some example code on how to do that.

A 302 redirect would probably be more appropriate than 301. You wouldn’t want Google to think that http://example.com/ should always really be http://example.com/en/ or whatever this script might end up sending it to, and people could theoretically change their browser’s language preferences.

You also might want to include $_GET['p'] in your redirect location. Right now you’re just sending all traffic off to the locale-specific homepage, which is why 404s aren’t working as expected.

To put it all together, here’s what you might want to do:

<?php

// Make sure this isn't a CP request
if (!isset($_GET['p']) || strncmp($_GET['p'], 'admin', 5) !== 0)
{
    // Language paths
    $paths = array(
        'de' => '/de/',
        'it' => '/it/',
        'en' => '/en/'
    );

    // Get the browser's preferred languages
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && preg_match_all('/([\w\-_]+)\s*(?:;\s*q\s*=\s*(\d*\.\d*))?/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches, PREG_SET_ORDER))
    {
        $languages = array();
        $weights = array();

        foreach ($matches as $match)
        {
            $languages[] = strtolower(substr($match[1], 0, 2));
            $weights[] = !empty($match[2]) ? floatval($match[2]) : 1;
        }

        // Sort the languages by their weight
        array_multisort($weights, SORT_NUMERIC, SORT_DESC, $languages);

        // Find the first match
        foreach ($languages as $language)
        {
            if (isset($paths[$language]))
            {
                $matchingLanguage = $language;
                break;
            }
        }
    }

    // Default to German
    if (!isset($matchingLanguage))
    {
        $matchingLanguage = 'de';
    }

    // Redirect
    $url = $paths[$matchingLanguage].(isset($_GET['p']) ? $_GET['p'] : '');
    header('Location: '.$url, true, 301);
}
else
{
    // Path to your craft/ folder
    $craftPath = '../craft';

    // Do not edit below this line
    $path = rtrim($craftPath, '/').'/app/index.php';

    if (!is_file($path))
    {
        exit('Temporary error. Could not find the CMS folder.');
    }

    require_once $path;
}


No live preview available when entry status is set to disabled?

Live Preview will be available when the following are true:

The section’s “Entries in this section have their own URLs” setting is checked
The section’s “Entry Template” setting points to a valid template path
The entry has been saved

It doesn’t matter if the entry is enabled or not.


How can I set dynamic absolute Asset URLs?

If you want to use the {siteUrl} tag in your Asset source settings, you'll still additionally need to define it in your environment variables as well.

See here as well.


You can simply load the file normally via php require once

require_once( __DIR__ . '/resources/DateFormatting.php');
$dataFormatter = new DateFormatting();

From your plugins init function or where ever you would like to call it.

Edit:

I hope your DateFormatting is not like you posted it because it has no functions. Btw Craft::import() has the advantage that you can import entire folders and it loads the class only to Yiis classmap which means that it is only loaded when you need it and not until then. If you want to use the file for sure, require once is the better way since Craft/Yii does the same in the very end.

Edit2:

Never mind, Yii uses include and not require_once, sry for the wrong info here. However... today the difference is not that big issue. Comparison include vs require_once


Find Entries with Multiple Matches in a Single Field

The main problem is your URL isn't formatted correctly. You need brackets after each 'size' parameter to make an array of those values. Otherwise, it only picks up the last value.

http://domain.com/search/results?size[]=small&size[]=medium

Then you can do something like this:

{% set sizeQuery = craft.request.getParam('size') %}

{% set params = {section: 'shorts', limit: null} %}

{% if sizeQuery %}
  {% set params = params|merge({'size':sizeQuery}) %}
{% endif %}

Also, you can use the dump() function to test what craft.request.getParam('size') is finding in your URL.

{{ dump(sizeQuery) }}

This URL: http://domain.com/search/results?size=small&size=medium

... returns string(5) "medium".

But this URL: http://domain.com/search/results?size[]=small&size[]=medium

... returns array(2) { [0]=> string(5) "small" [1]=> string(5) "medium" }.


Show active parent's listed children when viewing it children

I think you're looking for the getSiblings() method. This will return all sibling entries for the current entry. You can also use getParent() to get the parent entry and getChildren() to get the entries child entries.

An example implementation is below:

{% set siblings = entry.getSiblings() %}
{% set parent = entry.getParent() %}
{% set children = entry.getChildren() %}

{% if parent|length %}

Parent

{{ parent.title }}

{% endif %}

{% if siblings|length %}

Siblings

  {% for entry in siblings %}

{{ entry.title }}

  {% endfor %}
{% endif %}

{% if children|length %}

Children

  {% for entry in children %}

{{ entry.title }}

  {% endfor %}
{% endif %}

More info on these methods can be found in the EntryModel documentation.


What I do is I listen for the Plugins::EVENT_AFTER_LOAD_PLUGINS event, and then do my code that relies on other plugins being loaded:

    // Handler: Plugins::EVENT_AFTER_LOAD_PLUGINS
    Event::on(
        Plugins::class,
        Plugins::EVENT_AFTER_LOAD_PLUGINS,
        function () {
            // Do stuff only after all other plugins have loaded
        }
    );


You'd most likely need to write a custom plugin. I think it might be doable (but maybe not advisable) with Twig.

The plugin would contain an array of the entries in the sequence. How you specify this is up to you. It could be from within plugin settings, or a specific entry, or even just hard coded into your plugin.

Then you need to create some way to store user ids against the last entry they watched and a date. Perhaps in a database table created by your plugin. Alternatively each user would have a custom field on their profile that contained the ids of the last entry they viewed plus the date they watched it.

When visiting the url for an entry, there is a check performed against that field.
If this is the next entry in the sequence, and sufficient time has passed since they viewed the previous entry then allow them access. Also update the database table (or their hidden profile field) with the new entry ID and current date.

It's really down to scoping out the exact way you want it to work, not worrying about the method or code involved. Once you've got that you can determine how to write the plugin.


Custom fields are attached to Users, not User Groups.

Seems like you'd be able to do what you want on the template side, though.  i.e. something like "if user is in group A, show field B, otherwise hide it".

Or perhaps something like the Reasons plugin is the way to go, which adds conditionals to fields/field layouts.


Need to access each item's converted price from payment gateway

At the moment there is no multi-currency support built into Commerce.

Meaning, all prices in the system are stored in a single currency. This includes products, shipping, taxes, sales, discounts.

We DO have a multi-currency payments feature that allows a customer to pay in another currency (so they are charged an expected amount and get no surprises with their banks own conversion ratio).

The issue you are hitting above is that the price of the products is never converted. The items in the 'item bag' can only exist in the primary currency.

Your best bet is to not send the item bag to the gateway and only have them charge the amount. You can do this with the setting: sendCartInfoToGateways https://craftcommerce.com/docs/configuration#sendcartinfotogateways

If we were to try and get clever and convert the line items prices to the differing payment currency, the amount to be paid would work out to be different to the converted total, due to rounding.

When we move to full multi-currency support, this issue would go away since the line items would be converted first (along with discounts etc), and the total would be a sum of those amounts.

Hope that helps.


How do I resolve dependency conflicts in Composer?

I was able to take your composer.json file, run composer update from it without any issues, do an install of Craft from that and update Craft/plugins and install/uninstall Craft/plugins from the Control Panel without any issues.

symfony/yaml v4.1.0 requires php ^7.1.3 -> your PHP version (7.2.14-1+ubuntu18.04.1+deb.sury.org+1) overridden by "config.platform.php" version (7.0) does not satisfy that requirement.

For that one, you've got this in your composer.json file:

  "config": {
    "sort-packages": true,
    "optimize-autoloader": true,
    "platform": {
      "php": "7.0"
    }
  },

Change it to this:

  "config": {
    "sort-packages": true,
    "optimize-autoloader": true,
    "platform": {
      "php": "7.2.14"
    }
  },

And it will go away.


Plugin Development (Craft 3): Pass variables with redirection

Try this:
Craft::$app->getUrlManager()->setRouteParams([
               'variables' => ['order' => $order]
             ]);


Pathed URL creation from templated files

You can use the ~ (concatenate string) operator to build the URL manually:

{{ url('/discount/discount/view/'~entry.id~'-'~entry.slug) }}


Display entries if Field Date is past Now

You can combine a for and if statement in twig, so you don't necessarily need to use search.

Something like this might get you a bit closer:

{% for entry in craft.entries.section('event') if entry.postDate < now %}
{# output your event here #}
{% endfor %}

It'll just output what meets the criteria if your if statement. The bonus is it doesn't mess with your loop variables either, so things like loop.index work out as you'd expect (or at least they have for me so far).

EDIT: Here's an alternate way of doing it, which neatens up the query and adds ordering...

{% set events = craft.entries({
    section:  'event',
    startDate:  '< ' ~ now,
    order: 'postDate desc'
}).find() %}

{% for event in events %}
...
{% endfor %}


Order tags by count - e.g. Top 10 Tags Used

This is based on Matt's answer to your previous question. Likewise this should better be used within cache tags!

This is untested, but it hopefully works out for you.

.

Edit:

This is still untested but it came to my ears, that it could make problems to assign variables as array keys. That's why I changed the code to use objects instead. If anyone uses this code, I'd be happy to hear if it does actually work!

{# Get all tags #}
{% set allTags = craft.tags.find() %}

{# Define object outside the for loop #}
{% set weightedTags = [] %}

{# Iterate over all tags #}
{% for tag in allTags %}

    {# Get total number of tag occurrences in entries belonging to 'blog' section #}
    {% set count = craft.entries.section('blog').relatedTo(tag).total() %}

    {# Save tag id and count to our weightedTags object #}
    {% set weightedTags = weightedTags|merge([{ tagId: tag.id, tagCount: count }]) %}

{% endfor %}

{# Sort, reverse-sort and pick top 10 elements of the array #}
{% set weightedTags = weightedTags|sort|reverse|slice(0, 10) %}

{# To print the top 10 list iterate over our weightedTags array #}
{% for tagObject in weightedTags %}

    {# Get tag object for each tagId #}
    {% set tagEntry = craft.tags.id(tagObject.tagId).first() %}

    {# Return the list item #}
    {{ tagEntry.name }}

{% endfor %}


Live Preview not working - showing home page instead

My bad. I forgot to call the block in the _layout template!


Unavailable plugin during migration to craft 3

When updating from Craft 2 to Craft 3, you will need to make a handful of decisions on how to handle plugins that don't have a clear migration path. The answer may be different for each plugin, depending on various circumstances.

Moving forward with dead plugins, you'll generally need to...

Replace it with a completely different plugin, or
Port some version of the necessary code into a custom module, or
Figure out how to replicate that behavior using native Craft features, so you can skip using a plugin or module completely.

If you bought a Craft 2 license for the plugin, see if there is a way to transfer your license to Craft 3. How this is handled will vary greatly between plugin vendors, so you'll need to follow up with the plugin vendor directly.
For custom plugins, you'll want to convert those into a module. It's like a plugin, but different.


Does Craft support gated content and form fills?

Craft is definitely a good fit to manage content around these workflows, but the workflows themselves will require a bit of planning as to how they get implemented.

While there are several potential solutions, I'll share one workflow that can be used for this type of content using the Sprout Forms plugin (which my team is behind).

Create a Landing Pages or Events Channel in Craft. Add whatever fields you want to customize your Landing Page or Events however you need to. These fields can be related to the content, layout, design; event information; or promotional content like the items you mentioned (ebook, white paper, etc)
Create a Form in Sprout Forms for each type of lead capture form you want. You could have one that just requests an email; another that requests name, email, and a few other details; and another that let's a user select which event Date/Time they want to participate in.
On the Landing Page Channel add the Forms Relations field. This will allow you to build flexible Landing pages with variations on your layout and design, as well as relate the form that you want to the Landing Pages or Event pages you are going to be sharing with your users.

After a user submits a form they will be redirected to a thank you page that you can set in the form settings. Depending on how you'd like to protect any content there are several different ways you could grant access to the page, but you have complete flexibility (some of these methods may require more setup than others):

Just redirect and share the confirmation info or marketing content
Redirect with a token that enables the content on the thank you page to only be seen by someone submitting the form
Trigger an email to the user who submits the form with a unique link to the content you want them to have access to


How do I preserve user sessions across subdomains?

Figured this out, the appId setting was the culprit: https://craftcms.com/docs/config-settings#appId

If using this setting, you probably don't want to set it to something dynamic (as I was, e.g. md5($url)).


I have added a prototype plugin that uses Pusher.com to keep track of online users.

Check out the Git repo.

Basically you need to add this to your frontend template:

{{ craft.whosaround.setup }}

It adds the Pusher library, and also subscribes to the channel name you got in your settings. You need to signup to an account over at Pusher.com as well.

In the CP, you can get a rudimentary list with the name and the count.

I can think of some cool use cases, so I'll probably revisit it soon and add more stuff etc., but it might be a useful starting point, depending on if you want to use Pusher for this.

Pusher is a very neat service for use cases like this, and might be especially interesting if you expect many users online.


Passing null values to queries, Sprout Reports

Yes, the post you linked to is what you need to do.
I don't know where your settings variable is set so you may need to adjust a bit but something like this should get you started:
{# Start your element query #}
{% set query = craft
    .entries()
    .section('purchases')
%}

{# Check if settings.userId, if so, apply it to the query #}
{% if settings.userId %}
    {% set query = query.authorId(settings.userId) %}
{% endif %}

{# Run the query #}
{% set purchases = query.all() %}


Uninstalling a plugin from Craft control panel

Settings > Plugins
There you will find a pulldown for each plugin with an uninstall option.


To fix that particular error, you'd need to bump your php.ini file's max_execution_time setting to something higher than 30 seconds to allow more time for the request to complete.


How can I limit the rows returned in a table field?

According to the Craft docs , the table field returns an array of rows.

Assuming that is the case, you should be able to use the Twig slice filter:

{% for row in registration.registrationCost | slice(0, 3) %}

You can then use a simple conditional to output the row divider:

{% if loop.index == 3 %}
    <hr>
{% endif %}

Stephen


It sounds like you're running into a bug in the latest version of Craft (2.4.2675) where transforms are broken for source asset files that end in an uppercase file extension (.JPG, .GIF, etc.).

It's already been fixed for the next release, but as a workaround you can rename the extensions to be lowercase and re-index your assets.


Craft Commerce starting order ids form a higher number?

You can write a Craft plugin that listens to the onBeforeOrderComplete event and implement whatever sort of order number format your business requirements require.

Alternatively here's an existing plugin that uses that method that might already cover your needs: https://github.com/bossanova808/CommerceFriendlyOrderNumbers


syntax error, expecting variable (T_VARIABLE) in Search Plus Custom Mapping

That is a typo in the plugin's documentation.

public function testMapping(element)

should be

public function testMapping($element)

since $element is a PHP variable.


You can by using this: {{ include(template_from_string(entry.fieldName)|raw) }}

You could also try it with just |raw But that probably only works for just HTML

This works on both a Plain Textfield aswell on a Richtext area. Although I wouldn't recommend putting code in your textfield's like that.

The original answer on a simular question can be found here: https://craftcms.stackexchange.com/a/1270/3848


How can my plugin generate a generic modal window in the Control Panel?

Create a div with whatever contents you want in the modal, and with a class "modal". Then create a new Garnish.Modal object with it:

var $div = $('
...
');
var myModal = new Garnish.Modal($div);


How can you use the jQuery pjax plugin with Craft?

In order to make an AJAX call in Craft, you'll need to build a custom plugin. Within the context of your plugin, add a Controller as the end-point for your AJAX call. Once you've setup your controller, take a look at the EntriesService API methods to sort out exactly how to retrieve your entry data.

If you've never built a plugin or are unsure of where to begin, you can download this Business Logic template to use as a starting point. It comes pre-packaged with a controller containing a simple AJAX call (and a lot of "how-to" notes).

If you have any follow-up questions along the lines of "how do I collect the data for my AJAX call", those would be worthy of being their own Stack Exchange questions.


Is there a way to populate a drop-down with the templates files in a folder?

This would be a good task for a plugin.

You'd essentially need to build the plugin to do a couple of things:

(1) Use PHP in a service to list the contents of a directory. Once you have that list, you'd then need to...

(2) Deliver that information to the front end via a custom field type. You can then use your new custom field type wherever you'd like.


Does Craft Commerce support multi-channel fulfillment and inventory?

The short answer is, out of the box, no it does not, currently.  Inventory handling is quite basic at the moment, for example.

You could probably deal with a lot of the access stuff via Craft users & permissions, but there's no doubt in my mind this would involve a very substantial amount of custom plugin development work, and I'm reasonable sure no such plugin currently exists.

Commerce is still a relatively young product, so who knows about the future, but right now it would not personally be my first choice for this sort of project.

(You could perhaps tackle them as separate installations and use things like the ElementAPI to push product content between the systems, though, if the key issue is content sharing as opposed to one unified back end).


This is all pretty well documented here: Creating Optimized Images in Craft CMS

But if you need general help on srcset and <picture> elements check out Responsive Images Done Right: A Guide To  And srcset and Don’t use  (most of the time)


There is a PR to fix this, in the meantime, you can add use craft\feedme\events\ElementEvent; at the top of vendor/craftcms/feed-me/src/base/Element.php


Sure, works just the same. Just change method="GET" to method="POST".

You can acquire the POST values by using craft()->request->getPost('yourPostName') in your plugin controller or by using {{ craft.request.getPost('yourPostName') }} in a template.


php.ini crashes CP with "Craft requires the PDO extension to operate."

I fixed this by adding the PDO extensions in to my php.ini which was overriding the server one.

extension = "pdo.so"
extension = "pdo_sqlite.so"
extension = "apc.so"
extension = "intl.so"
extension = "pdo_mysql.so"


P&T Contact Form v1 adding code for 'beforeSend'

Correct way is little bit longer.

Firstly, you need your own plugin, you can generate skeleton here: https://pluginfactory.io/ It's better than rewrite someone else's, because you can't update it after you add a code.

Secondly, you add your beforeSend Event to Plugin class by add it to init function - the function will be generated in step one - it is in the YourNamePlugin php file in root.

If you start a new project, it is better to work in Craft 3.


When you include the library as required in your composer file, Craft will automatically download the package and install it in the global vendor directory rather than in your plugin directory (since both are inside the vendor folder).

You don't have to include it and you don't have to take care for certain other plugins that require the same one.

This process is done while running composer install >>yourplugin<< or composer update so everytime you make a Craft update it will search for new required libraries in your plugin but it won't do it during the installation of your plugin since every library should already exist - unless you add the dependency after your composer action -> composer update will solve it


Commerce Stripe Authorize Only - Capture partial amount in Craft admin panel

As of Commerce 2.0.0-beta.7,  partial capture is not yet supported. Look out for it in the next release.


Javascript events when modal window is opened or closed

This is what I ended up doing:

https://github.com/nystudio107/disclosedassets/blob/master/resources/js/disclosedassets.js

There is a Garnish.Modal.visibleModal that will contain the handle to the Garnish modal object if one is visible. You can use this to see if a modal is visible, and even see which one.

Unfortunately there's no event I'm aware of that triggers when a modal is shown, so you'll still have to poll via window.setTimeout() -- it's a hack, but...


Get the ID of a new entry when it's saved

If you wanted to do this without having to write your own plugin, you can achieve this with a simple custom route and an extra parameter in your template.

Your hidden fields could look like:

<input type="hidden" name="action" value="entries/saveEntry">
<input type="hidden" name="redirect" value="schedule/{id}">

And then in config/routes.php put

'schedule/(?P<id>\d+)' => 'scheduleTemplate',

When craft saves the entry, it will redirect you to schedule with the ID of the entry that was just saved as the last segment. The custom route will pick up any digit on the end of the url and assign it to a variable called id which you can then use in your templates.

Some behind the scenes clearance, based on your comment

No they aren't twig variables as the replacement is doing through php (although apparently you can use Twig tags).

When you save an entry the new entry object gets passed in redirectToPostedUrl which, if there is an object passed will call the function renderObjectTemplate in the templates service, this will swap out any {single} or {{twig}} tags with the appropriate attribute and you will get the finished URL returned.

Here are two links to the class reference so you can see what I mean.

The redirectToPostedUrl function

The renderObjectTemplate function


How to load a different template for parent page

First, I'd recommend that you have a total of 3 templates: _child.html for your child entries, _parent.html for your parent entries, and finally _entry.html which will basically work as a "controller" template (the only code contained in _entry.html should be the code that includes either the child or parent templates). You can, of course, name the templates whatever you want, but make sure that the Section's entry template is pointing to _entry.html.

Then, put this in your _entry.html file:

{% switch entry.level %}
    {% case 1 %}
        {% include '_parent.html' %}
    {% default %}
        {% include '_child.html' %}
{% endswitch %}

What the above does, is simply to look at the entry.level attribute, which returns the level your Structure entry is at. Top level entries are level 1, so for a simple 2-level Structure, this may work.

If you need something more flexible, where a "parent" template should be loaded unrelated to levels but based on whether an entry has children or not, you could do something like this (also in entry.html):

{% if entry.children|length %}
    {% include '_parent.html' %}
{% else %}
    {% include '_child.html' %}
{% endif %}

Another option is to test for an entry's parent property instead (i.e. if an entry has a parent entry, it should load the child template):

{% if entry.parent %}
    {% include '_child.html' %}
{% else %}
    {% include '_parent.html' %}
{% endif %}

Note: You may need to correct the paths to your templates for the examples above – the {% include %} always works relative to your /templates folder, so if your templates actually live inside /templates/news, you'd have to use {% include 'news/_parent.html' %} (even if _entry.html and _parent.html is inside the same folder).


Thanks for your reply! We'll look into Solspace Calendar which appears to be very powerful and should fulfil our requirements.


Not sure if you really wanted dynamic variable names like imgurl1 or not, but something like this?

{% for entry in entries %}
    {% set loopIndex = loop.index %}

text{{loopIndex}}

    {% if loopIndex is divisible by(3) %}
        {% if not loop.last %}

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


This should get you going in the right direction: https://craftcms.com/guides/displaying-tags-that-are-in-use


How to reference Twig form values from within controller action?

You can use craft()->request->getPost('name') to grab any posted values from your form submission.


Possible to override Garnish.Modal? [Plugin]

By default, Garnish.Modal will automatically close other modals when show() is called (which happens automatically when you first create it).

That behavior can be overridden by setting the closeOtherModals setting to false, though:

var myModal = new Garnish.Modal($container, {
    closeOtherModals: false
});


Admin assets not being served over https

So I added the following lines to my nginx file and it all worked

location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
    try_files $uri /index.php?$query_string;
}

location ~* \.(?:css|js)$ {
    try_files $uri /index.php?$query_string;
}


You could have a single News section that is enabled for each of the locales, and choose which locale each entry should target from their Edit pages.

To make it easer on the authors, you can set the default status to Disabled for each of the locales, from the section’s settings. Then when creating a new entry, the authors only have to enable the one locale that they actually want the entry to be published for.

Update

As of Craft 2.6.2972, you can configure the Entries index to only show entries that are enabled for the selected locale by installing the CP JS plugin, and pasting this code into its “Additional JavaScript” setting:

Craft.defaultIndexCriteria.localeEnabled = true;

You also may want to add this bit, to ensure that entries’ locale statuses are switched on by default from the Edit Entry page, so they don’t get lost in the entry index, which is now configured to only show locale-enabled entries:

$(document).ready(function() {
    var ls = $('#locales .lightswitch').data('lightswitch');
    if (ls) {
        ls.turnOn();
    }
});


Have a look at the settings of your asset's volume:
Go to: Settings > Assets > [Your Volume Name here]
Check the field "Base URL". If it starts with the alias @web, remove it.
E.g. "@web/images" -> "/images".
Now check the URL of your image again.


Is it possible for photo's to be uploaded to a form?

As mentioned in Oli's comment, there's an example of how to do this in the documentation: https://docs.craftcms.com/v3/assets-fields.html#uploading-files-from-front-end-entry-forms


Craft Commerce: Hard code different product prices based on currency?

You can add custom fields to store the 'other' price for your products (and/or variants), like, as you say, a matrix, or probably even a table would do.  The fields can then be edited by admins in the back end.

In your templates, you'd selectively display whichever price the particular market needs - this would just be basic template logic.

Then, you'll also need a simple custom plugin that listens to onPopulateLineItem and checks which market the customer is in, and modifies the lineItem price accordingly (by retrieving the correct price form the appropriate field).  Once the lineItem prices are modified as appropriate, they'll be used for the payments and stored with the order, factored into totals etc.

There is an example of modifying a lineItem in the docs here:
https://craftcommerce.com/docs/events-reference#commerce_lineitems.onpopulatelineitem

Unless you have other requirements not mentioned, for someone with Commerce experience, that would be really be quite simple to implement.

(Based on ~ a years work with Commerce and related plugin writing).


If you want to search for entries, you can use the search parameter:

{% set people = craft.entries
    .section('people')
    .search('*xyz* OR *zzzz*')
%}

Then, you can loop through those people like this:

{% for person in people |batch(3) %}
    {{ person.name }}
{% endfor %}

By default, search doesn't do fuzzy search, that's where the *s come in. You can, however, enable fuzzy search by default.

If you want to limit your search to a field, do:

{% craft.entries.search('fieldHandle:xyz OR fieldHandle:zzzz') %}


What is the difference between siteUrl and baseUrl?

When you take a look into Craft you'll see this

 /**
 * @var string|string[] The base URL to the site(s). If set, it will take precedence over the Base URL settings in Settings → Sites → [Site Name].
 *
 * This can be set to a string, which will override the primary site’s base URL only, or an array with site handles used as the keys.
 *
 * The URL(s) must begin with either `http://`, `https://`, or `//` (protocol-relative).
 */
public $siteUrl

So the baseUrl is what you insert in your site settings, the siteUrl can overwrite these values from your config

The Site.php (model) has a this function as well

/**
 * Overrides the base URL while keeping track of the original one.
 *
 * @param string $baseUrl
 *
 * @return void
 */
public function overrideBaseUrl(string $baseUrl)
{
    $this->originalBaseUrl = (string)$this->baseUrl;
    $this->baseUrl = rtrim($baseUrl, '/').'/';
}

which is called in the Site service

$site->overrideBaseUrl($generalConfig->siteUrl);


My tasks don't seem to be running as a background process

You are right about the Tasks running in the background. If the Task is just sending a few mails, it might be done before your site is loaded, thus creating this impression.

Check:

Change the Batch Size of the Mailer plugin to 1 and the waiting time to 120 seconds.
Change the $user_criteria to fetch 2 users.
Run your controller

It should now take about 2 minutes for the Task to finish, if your site loads faster it was just an impression.

Code:

You should however separate your code a bit more, because right now you are mixing Controllers and Services.

Your Service shouldn't output anything, it should just return a value, (e.g. boolen), and your Controller should then output the message:

Service {
    //Create Task etc...

    if ($itWorked == true) {
       return true;
    }
    else {
       return false;
    }
}

/* ------------------------ */

Controller {
    if ( FunctionService() ) {
       echo 'It worked';
    }
    else {
       echo 'Something went wrong';
    }
}

Also the "Make sure we kick the task off"-part, should go into your Service.

P.S. I see you are using my plugin :), if you need any help, create an issue over on github.


Craft Commerce View Order PDF, Not Download

No, I don't think there's a way of having a "live" pdf open, in the same way as a webpage.

But, what I usually do is just open the pdf template directly in the browser and create the HTML and CSS while using my normal workflow to check how it looks in the browser. This usually get me 95% of the way, and then I can do the final tweaks when I see what dompdf makes of it.

You need a variable order that's an OrderModel to make this work, so I just grab one like this at the top of my template or in my layout:

{% if not order is defined %}
    {% set order = craft.commerce.orders.first() %}
{% endif %}

And if you want to test with different orders you can get one at random, or a specific one by id.