Sort entries by global variable category

One solution is to retrieve the entry ids for the season entries and all entries separately; subtract the 'season entry ids' from 'all entry ids' (using craft's without twig filter); then merge the two arrays back together (using twig's merge filter) in the proper order. You can then use this new id array to generate an elementCriteriaModel which can be used in your paginate expression.

{% cache %}
    {% set season = season.season.first() %}
    {% set seasonEntryIds = craft.entries.section('generalContent').relatedTo(season).order('lft desc').ids() %}
    {% set allEntryIds = craft.entries.section('generalContent').order('lft desc').ids() %}
    {% set nonSeasonEntryIds = allEntryIds|without(seasonEntryIds) %}
    {% set sortedEntryIds = seasonEntryIds|merge(nonSeasonEntryIds) %}

    {% paginate craft.entries.id(sortedEntryIds).fixedOrder(true) as entries %}
        {% for entry in entries %}
            {{ entry.title }}<br>
        {% endfor %}
    {% endpaginate %}
{% endcache %}

Since there are a lot of queries happening here, it might also be a good idea to wrap the code in 'cache' tag.


Getting Checkboxes to work on Frontend Forms

The first loop you're using loops over entry.gistCategories.options, which contains all the options available. However, in the second loop (when entry.gistCategories|length !== 0), you're only looping over the options that have been selected.

Try this:

{% if entry.gistCategories | length == 0 %}

        {% for option in entry.gistCategories.options %}
            {# output checkboxes #}
        {% endfor %}

{% else %}

        {% for checkboxOption in entry.gistCategories.options %}
            {# output checkboxes #}
        {% endfor %}

{% endif %}


Craft does have the maxUploadFileSize config setting (defaults to 16MB).  If what you're trying to upload is under that size, you're probably running into environmental limitations.  I'd check your php.ini file's post_max_size, memory_limit and max_execution_time settings as a starting point.


The problem you're probably facing isn't that URLs like

http://example.com/en/news/example
http://example.com/fr/nouvelles/exemple

don't work, but that you're not getting the sections' index pages to load because they're just a index.html file in your templates/news/ folder (→ routing case 6 in https://craftcms.com/docs/routing).

For a multi locale setup with translated slugs it's recommended to not rely on "URI to template matching" at all and create an entry or category for every page, so Craft sets up the routes for all the translated slugs automatically (→ routing case 4).

In your case you'd just create an entry for your News index page, e.g through a single section. In the single section's settings set up the URLs for your locales and route them to your template.


Plugin Settings: Attribute Types, and how to receive

As far as accessing the value of the setting, try:

$plugin = craft()->plugins->getPlugin('pluginHandle');
$plugin->getSettings()->getAttribute('pluginSettings1');

If you need to access your settings throughout your services file you might also create a global variable.

class PluginHandleService extends BaseApplicationComponent
{
    public $settings = array();

    public function __construct()
    {
        $this->settings = $this->initSettings();
    }

    private function initSettings()
    {
        $plugin = craft()->plugins->getPlugin('pluginHandle');

        $settings = array();
        $settings['pluginSettings1'] = $plugin->getSettings()->getAttribute('pluginSettings1');

        return $settings;
    }

    // other service methods

}

Which you can then access like this:

$this->settings['pluginSettings1']

Thanks to André Elvan for help on setting up a constructor.

Update

As far as assigning a value however, I think you may have to use the 'default' property. In the past I have successfully done this with strings like so:

protected function defineSettings()
{
    return array(
        'pluginSettings1' => array(AttributeType::String, 'default' => "value"),
}

I presume you could do the same with 'Mixed', although never tried:

protected function defineSettings()
{
    return array(
        'pluginSettings1' => array(AttributeType::Mixed, 'default' => 'active_features' => array('change_team' => false, 'change_series' => false, 'change_user_settings' => false))),
}

It might make more sense to break the array into individual settings, however.

protected function defineSettings()
{
    return array(
        'change_team'          => array(AttributeType::Bool, 'default' => 'false',
        'change_series'        => array(AttributeType::Bool, 'default' => 'false',
        'change_user_settings' => array(AttributeType::Bool, 'default' => 'false',
    ),
}


Limit Users Signup to Users from Specific Domain

Probably best to do all of this from a custom plugin (that way you can write the logic for the approval process).

But regardless, you can do something like this from the top of your template:

{% if craft.request.getServerName() is not "mydomain.gov" %}
    {% exit 503 %}
{% endif %}

And similarly any controller actions would have:

if (craft()->request->getServerName() !== 'mydomain.gov" )
{
    throw new HttpException(503);
}


@crawf was right with his answer, but I recently saw the preview release for Craft 3, so Placid 2 is going to wait and be written for that.

So I thought I should fix the current version of Placid to work with the latest version of OAuth (currently 0.9.71) and as a brucie bonus you can now connect to more than just the twitter api :)

You can get the latest version (1.3.0) on github and any issues just give us a shout on the repo (or here, whichever you feel most relevant)


Just added this note to the Plugin Templates documentation, which should answer your question:

  Craft will only automatically look for templates within the plugin folders for CP requests. If you are going to be calling TemplatesService::render() from a front end site request, you will need to manually tell Craft where to find your template using PathService::setTemplatesPath() first:

$oldPath = craft()->path->getTemplatesPath();
$newPath = craft()->path->getPluginsPath().'pluginHandle/templates';
craft()->path->setTemplatesPath($newPath)
$html = craft()->templates->render('path/to/template');
craft()->path->setTemplatesPath($oldPath);

  If you do this, you won’t be needing to begin the template path with your plugin handle.


Hide flagged (inappropriate) comments from comment list

You can use the isFlagged() method to only display non-flagged comments:

{% set comments = craft.comments.all({
    limit: 10,
    status: 'approved'
}) %}

{% for comment in comments if comment.isFlagged() == false %}
    {{ comment.comment }}
{% endfor %}


Output of matrix field twice in one template

Here's how I would approach this...
{% set classBlocks = entry.classBlocks.all() %}

{% if classBlocks | length %}
    {% set instructors = classBlocks | filter(block => block.type == 'instructors') %}
    by <strong>{{ instructors | map(instructor => instructor.fullName) | join(', ', ', and ') }}</strong>
{% endif %}

We're using several filters here to achieve what I think you're trying to achieve:

| filter is used to filter just the instructor blocks out of all your class blocks; this saves us from having to do the cloning and extra query mess and is more performant.
| map is used to take our array of instructor blocks and return an array containing just their names.
| join is used to take the array of names and create a nice readable list (I find it cleaner than doing the loop checking like you're doing) - e.g. "Bob, Matt, and Susy"

Let me know in the comments if you have any questions or if I'm not understanding the question correctly!


Craft Commerce — Update order status from frontend?

This feels a bit dirty, but you can actually do this directly in a Twig template like this:
{% set order = craft.orders.id(123).one() %}
{% do order.setAttributes({orderStatusId: 4}, false) %}
{% do craft.app.getElements().saveElement(order) %}

-- naturally you'd need a way to fetch which order you want to update, but you could easily grab that from your POST data or from the URL or localStorage or whatever.


Craft Commerce ajax add to cart, missing information

As Brad said in his answer, what you get back is the lineItem details - enough to update e.g. your totals, shipping quote etc.

The URL of the product, and the product fields etc, are not available in the JSON.  But it's hard to see why they would need to be - you're sending this ajax call from somewhere you already have a reference to the product/variant in your twig templates - why would you need this info repeated in the return object?

If you really need that stuff at that point, you're probably better off ajax loading in a twig template to get at the full product stuff.  If you could clraify what you're actually trying to do I can probably help better/describe what we've done.


Getting redirected to login page on every other CP request when using Vagrant

I kind of doubt this is it, but Craft does have a couple of config settings that might be coming into play here.

You can tell if you're being affected by these by looking in your craft/storage/runtime/logs files and see if there are any messages being logged with a [warning] related to not being able to restore session.

If you are being affected by those, try setting both of them to false just to see if that helps.


Alright, so turns out all I need to do is comment out the following line in index.php:

define('CRAFT_ENVIRONMENT', getenv('ENVIRONMENT') ?: 'production');

Now I can use config.php keys, same way I did in Craft 2. For example:

'*' => [
    // My default/production variables
    'devMode' => false,
    etc...
],
// Local
'address.test' => [
    // Local variables
    'devMode' => true,
    etc...
]
// Staging
'staging.address.com' => [
    // Staging variables
    'devMode' => true,
    etc...
]

Thanks to Luke James for the assist on Slack.


Craft install locally with MAMP Pro/versioning

Here is how I have set things up in the past using a similar workflow.

When you get Craft out of the box (for lack of better words) as you said there is a craft folder and a public folder. Generally you want your craft folder above/out of your web root. That would look something like this:

craft/
   |- app
   |- config
 ...

public/
   |- index.php
   |- robots.txt

When setting up your site, point your doc_root to the public/ folder.
For example, if you are using a Mac, a default doc_root might look like this:

<VirtualHost *:80>
    ServerName sitename.dev
    DocumentRoot "/Applications/MAMP/htdocs/sitename/public"
</VirtualHost>

If successful, you should see a screen saying that your site is unavailable. I can't remember the exact verbiage.

From there I will edit two files:

/craft/config/db.php
/craft/config/general.php

db.php

return array(
    '*' => array(  // Global configuration
        'tablePrefix' => ''
    ),
    '.dev' => array( // local configuration
        'server' => '127.0.0.1',
        'user' => 'username',
        'password' => 'password',
        'database' => 'database'
    ),
    '.com' => array( // production configuration
        'server' => 'hostname',
        'user' => 'username',
        'password' => 'password',
        'database' => 'database'
    )
);

general.php

return array(
    '*' => array(
        'cpTrigger' => 'your-custom-admin-url',
        'omitScriptNameInUrls' => true
    ),
        '.dev' => array(  // local configuration
            'devMode' => true,
            'siteUrl' => 'http://mysite.dev/',
            'environmentVariables' => array(
                'basePath' => $_SERVER['DOCUMENT_ROOT'] . '/',
                'baseUrl' => 'http://mysite.dev/',
        )
    ),
    '.com' => array(  // production configuration
        'siteUrl' => 'http://www.mysite.com/',
        'environmentVariables' => array(
            'basePath' => $_SERVER['DOCUMENT_ROOT'] . '/',
            'baseUrl' => 'http://www.mysite.com'
        )
    )
);

By having the multi-environment settings like the above, you can commit your code and it will run regardless of environment.

Generally, I like to have a local database which is separate from my production db. My luck, I'll do something silly and delete something on accident. Depending on how big of changes you are making post-launch, I am sure there are good/better/best ways to migrate the updates to your production db vs. manually entering it. But, if they are simple things (added a new field) I usually just do that manually on my production server.

It sounds like if you can connect to your production db via a 3rd party tool, but not your application there might be some permission trouble (just a guess). Try working locally with everything first, then move it to your other server.

Hope this helps!


You could use the Craft/Twig |replace filter, which supports regex replacements.

Something like:

{% set handle = entry.section.handle %}

{% if handle == 'subSiteSectionHandle %}
    {% set newUrl = entry.url|replace('/regexMatchPattern/', 'replacedWith') %}
{% endif %}


UPDATE: As of Craft v2.2, the replace filter now supports regex:

  The replace filter now supports regular expressions, by setting the first argument to a string that begins and ends with forward slashes, e.g. '/foo/'.

So this should work by adding forward slashes.

{% set bar = '/%20AND%20foo%3A%22(.+?)%22/' %}

I think this is particular to Craft and not native to the Twig replace filter.

I don't think the Twig replace filter will allow for regex matches.

According to this post, Twig only uses regular expressions with Comparisons.

But there are third-party plugins which might work:

Twig PCRE Filters
Low Regex


Not finding template when adding "tag" view

And the winner is, routing... Adding in dynamic routing got me squared away.

If the URI looks like this: blog/*

Load this template: blog/index

One thing to note (as documented in the docs), your URI should not begin with a slash (/).


How do you gain PCI compliance without certifying your server for Craft, with or without Commerce?

The takeaway is to use api packages provided by payment providers such as Stripe and Authorize.net. The Craft Charge plugin can very much simplify and smooth doing so with Stripe.

Here's a link to a Git Gist of the conversation, as Slack erases content within a week:

https://goo.gl/bYIFLV

As well, though I don't guarantee it will stay up, is an experiment with Storify to show the same thing. I'm not sure which version reads better -- maybe Storify on a mobile phone, one reason for trying it.

https://goo.gl/5hEcLS


Yes but not like you tried it. You have to work on Yii2 level and not with Crafts Query

// prefix for content column tables
// if you want to select fields in the field layout do
// $prefix . 'fieldHandle'
$prefix = Craft::$app->getContent()->contentTable . '.' . Craft::$app->getFields()->oldFieldColumnPrefix;

$user = User::find()
    ->andWhere(
        new OrCondition(
            ['>','users.userLevel', 3],
            ['=', 'users.group', 'admin']
        )
    )
    ->all();

However: keep in mind this SQL will likely produce errors because there is neither a users.group column nor a users.userLevel column in the database

Just as an example for more complex search:

$prefix = Craft::$app->getContent()->contentTable . '.' . Craft::$app->getFields()->oldFieldColumnPrefix;
$criteria = [
    'where'     => new OrCondition(
        [
            [
                'between',
                $prefix . 'startDate',
                Db::prepareDateForDb($startDateDb),
                Db::prepareDateForDb($endDate)
            ],
            new AndCondition(
                [

                    ['=', $prefix . 'recurring', 1],
                    ['<=', $prefix . 'startDate', $startDateDb->format('Y-m-d H:i:s')]
                ]
            )
        ]
    ),
    'orderBy'   => ['startDate' => SORT_ASC],
    'sectionId' => 10,
];

$query = Entry::find();
\Craft::configure($query, $criteria);


Importing images from external url and saving to entry using plugin

Here's how I did it in a recent project:

    $fileIds = array();

    // get remote image and store in temp path
    $imageInfo = pathinfo($data['image_url']);
    $tempPath = CRAFT_STORAGE_PATH . 'runtime/temp/' . $imageInfo['basename'];
    file_put_contents($tempPath, fopen($data['image_url'], 'r'));

    // insert the file into assets
    $response = craft()->assets->insertFileByLocalPath(
      $tempPath,
      $imageInfo['basename'],
      $myAssetFolderId, // notice, this is the id of the folder you want to upload to
      AssetConflictResolution::KeepBoth
    );

    // if the response is a success, get the file id
    if ($response && $response->isSuccess()) {
        $fileIds[] = $response->getDataItem('fileId');
    }

    // create a new entry
    $entry = new EntryModel();
    $entry->sectionId = $mySectionId;
    $entry->typeId = $myEntryTypeId;
    $entry->authorId = 1;

    // set your content, including image field by id
    $entry->getContent()->title = $data['title'];
    $entry->getContent()->mainImage = $fileIds;

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

I included the entry saving part of it to show how the response is used to get the file id(s) and so on.

Whether this is the "correct" way to do it or not, I don't know. :)


There was a bug in Craft such that when saving a user, if the username / email / password failed validation first, content validation would never get a chance to run.

Have just fixed that locally and it will go out in the next release.
The way you have your dropdowns defined (userCountry and occupation), they'll never fail validation because there will always be a value selected and submitted in $_POST.
The first name and last name fields on a user account are somewhat “special” fields.  There is currently no way to set them as required.  We've got some plans to revamp how user names are handled on “The List”™ for a future update.  In the meantime, if you want to make them required fields, you can create actual custom fields for them.


How to prepend user input data to a filename uploaded through Sprout Forms

Sprout forms has hooks you can latch on to in your own custom module/plugin, so when a form is saved you can grab the asset and re-name at that point.


Speeding up the pageload of a page with a huge Matrix

Kind of a broad topic, but here are some resources to get your started:

Great article on Craft optimizations here: http://www.patpohler.com/performance-optimization-craft-cms/
Make sure your environment isn't a bottleneck.

You're not on an overloaded shared hosting server.
PHP has plenty of memory allocated to it.
Your server has plenty of resources (memory, CPU, disk space).
Run PHP 7.

Eager load elements as necessary: https://craftcms.com/docs/templating/eager-loading-elements
Judiciously use template caching in Craft where necessary: https://craftcms.com/docs/templating/cache
Enable devMode and review the profile output in the browser's console (as well as craft/storage/runtime/logs files to spot any bottlenecks (# of queries, types of queries, plugins involved, etc.)
Use template hooks as necessary.
Go through the plethora of client side things that can slow a page down. Google Pagespeed Insights is a good place to start for that.
If none of these work, you can looking into changing your content architecture so that 100+ Matrix blocks on one page aren't necessary.


Edit a checkbox field within table field from the front end

First, when you do this:

{% for row in currentUser.providerPayment %}

    ...

    {% for slidingScale in currentUser.providerPayment %}

you’re looping through the currentUser.providerPayment array (the rows in your providerPayment Table field on the current user) within another loop through the same array. If the table has 2 rows, this is what would be happening:

Row 1 (assigned to row)

Row 1 (assigned to slidingScale)
Row 2 (assigned to slidingScale)

Row 2 (assigned to row)

Row 1 (assigned to slidingScale)
Row 2 (assigned to slidingScale)

(Doesn’t make any sense.)

You only need a single for-loop here, and it’s the outer one. Within that loop, you will be able to access all of the values on the current row, via the row variable you’ve defined:

{% for row in currentUser.providerPayment %}

    {{ row.averageCostPerSession }}
    {{ row.slidingScale }}
    {{ row.acceptedPaymentMethods }}
    {{ row.acceptedInsuranceCarriers }}

{% endfor %}

Does that make sense?

So, for each row, if you want to output a checkbox input, you would just do this:

{% for row in currentUser.providerPayment %}

        <input type="checkbox" value="1"
            name="fields[providerPayment][0][col2]"
            {% if row.sliderScale %} checked="checked"{% endif %}>

{% endfor %}

One thing to keep in mind with checkboxes, though, is that they don’t actually submit any POST data if left unchecked. So to be safe, you should put a hidden input right before the checkbox input, with a blank value, which will act as the default value if the checkbox is left unchecked:

{% set name = 'fields[providerPayment][0][col2]' %}

{% for row in currentUser.providerPayment %}

        <input type="hidden" name="{{ name }}" value="">
        <input type="checkbox" name="{{ name }}" value="1"
            {% if row.sliderScale %} checked="checked"{% endif %}>

{% endfor %}


One way to include JS (or CSS) files, is to use the includeJsFile tag.
This tag will queue your file and append to the end of the <body>.
If, for some reason, you don't want this (say you want to include JQuery in the <head>), I would just use <script src=""> etc.

This might also solve your second problem.


How to shorten 'craft.request.getUrl()' with the shortener plugin?

The issue was that the custom short name I was using (in this case the development domain) was not associated with the bitly account.  Total oversight! I've removed that and it works perfectly.


Find Dropdown Option Labels That Are Assigned in a Section

I think you need to loop all entries of that sections to "collect" them.

{% set cocktailTypes = [] %}
{% for entry in craft.entries.section('mySection') %}
    {% set cocktailTypes = cocktailTypes|merge([entry.cocktails]) %}
{% endfor %}

{% for cocktailType in cocktailTypes|sort %}
    <p>{{ cocktailType }}</p>
{% endfor %}


AttributeType::Number giving validation error "Must be an integer"

Not really documented anywhere, but AttributeType::Number can accept an array of options, including min, max and decimal.  You're looking for the last one.

AttributeType::Number => array('min' => 0, 'max' => 10, 'decimals' => 2);


Iterate through Super Table field in plugin

Assuming your Super Table field has a handle of colors, you should be able to do:

foreach ($entry->colors as $block) {
    // Color will return a category element query, so you can do:

    // Return a collection of all category ids
    Craft::dump($block->color->ids());

    // Get the first category
    Craft::dump($block->color->one());

    // Get all the categories in the field
    Craft::dump($block->color->all());
}


Using the Redactor rich text field, how can I dynamically wrap my images with a fancyBox link (with attributes as parameters)?

I managed to achieve this a while back within ExpressionEngine. The approach would be the same...

I used this Javascript:

$(document).ready(function() {
    $(".fancybox").fancybox();

    // Apply FancyBox to images within the body of an article
    $(".articleBody img").on("click", function(){
       $.fancybox($(this).attr("src"),{
           // API options
           padding : 0 // example
       });
    });

    $('.fancybox-media')
        .attr('rel', 'media-gallery')
        .fancybox({
            openEffect : 'none',
            closeEffect : 'none',
            prevEffect : 'none',
            nextEffect : 'none',
            padding : 0,

            arrows : false,
            helpers : {
                media : {},
                buttons : {}
        }
    });

});

From memory, this worked on all  tags within .


As a more detailed reply to your comment:
You don't need to create a completely new section in order to have a different template. For Example when you create a section called 'Employment' you can have several different entryTypes in this section. In your /admin/settings/sectionsyou can see all your sections (left) and when you click on their entryTypes on the right you'll enter this page /admin/settings/sections/<sectionId>/entrytypes to edit them.

With the following folder structure you can do this:
|-/templates
|--/pages
|---_entry.twig
|---/entryTypes
|----imprint.twig
|----contact.twig
for example your section is called pages and you have the entryTypes imprint and contact.

Your section template is /pages/_entry.twig

{% extends [
    'pages/_entrytypes/' ~ entry.type ~ '.twig'
] %}

so depending on your entryType the template for imprint or contact will be rendered.

In your case you would create a folder Employment and create different entryTypes for the different templates you want to render. In your Employment you render the template depending on your need.
You can also extend your file to

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

so you can choose you template via slug/dropdown lists/checkboxes or whatever you want


Nginx config for craft working for everything but admin url's

Try adding specific location for admin & cpresources in the nginx config

location ^~ /admin {
    try_files $uri $uri/ /index.php?$query_string;
}
location ^~ /cpresources {
    try_files $uri $uri/ /index.php?$query_string;
}

before

location ~ [^/]\.php(/|$) {


Why is category.getUrl() returning incorrect subdomain?

Looks like the problem was using @web for the 'Base URL' setting in 'Settings > Sites'.

I replaced this with an environment variable BASE_URL="https://www.domain.com" defined in the .env file, and setting $BASE_URL in the 'Base URL' field.

No idea why @web doesn't work reliably here, but so be it.

Feel free to delete this question, but I thought I would leave it for others who may encounter the same problem.


How can I loop through a Channel entries asset folder?

I'm not sure about displaying "the first image from the asset folder" but, you can display the first asset as it's situated in the entry itself. Would that work? Maybe something like this?

{% set assetFirst = entry.myAssetsField.first() %}

{% if assetFirst %}
    {# or use getImg() (or either alias img/url): https://craftcms.com/docs/templating/assetfilemodel #}

{% endif %}

{% set assets = entry.assetsFieldHandle %}

{% if assets | length %}

    {% for asset in assets %}
        {# https://craftcms.com/docs/templating/assetfilemodel#simple-output #}
        {{ file }}
    {% endfor %}

{% endif %}


Where should the .all() be placed in Craft 3

Both approaches are valid. In your first example, you could have moved .all() into the for-loop; and in the second example, you could have moved .all() out of the for-loop, and into the {% set entries = ... %} statement.

Until you call .all(), you are working with an entry query, and after you call .all(), you’re working with an array of the actual entries (the query results).

So which approach is better depends on what else you’re doing in your template.

For example, if you need to output the total number of entries, you could do this:

{% set entryQuery = craft.entries()
    .section('news')
%}

{% for entry in entryQuery.all() %}
    ...
{% endfor %}

Total: {{ entryQuery.count() }}

But it would result in two database queries getting executed – once to get the entries for the for-loop, and a second query to get the total matching entries.

If you know you’re going to need that info, then it would be better to just fetch the entries ahead of time, and check the length of the array instead:

{% set entries = craft.entries()
    .section('news')
    .all()
%}

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

Total: {{ entries|length }}

Regardless of the approach you decide to go with, you might want to make sure you are using semantec variable names. In your two examples you have events (an array of actual event entries) and entries (an entry query).

I would say that if you are not going to call .all() when defining your entries variable, then you might want to rename that to either entryQuery or query, just so it’s easier to remember what sort of variable you’re working with later on in the template.

{% set entryQuery = craft.entries()
    .section('news')
    .orderBy('postDate desc')
    .limit('4')
    .with(['imageGallery'])
%}

{% for entry in entryQuery.all() %}
    ...
{% endfor %}


Multiple Queries with differing CSS in Paginated output

Well after a brain melting, I have come up with an answer, im not sure how pretty it is, any comments on how to tidy it up are most welcome.

{% set premEntries = craft.entries.section("test").relatedTo(category).Premium('yes').orderBy('RAND()').ids() %}

{% set standEntries = craft.entries.section("test").relatedTo(category).Premium('no').orderBy('RAND()').ids() %}

{% set premCount = craft.entries.section("test").relatedTo(category).Premium('yes').orderBy('RAND()').count() %}

{% set limitTotal = premCount / 12 %}

{% set limitRoundUp = ceil(limitTotal) %}

<1-- This gives me the number of premium entries on the last page they appear -->
{% set limitRoundDown = floor(limitTotal) %}
{% set lim3 = limitRoundDown * 12 %}
{% set lim4 = premCount - lim3 %}

{% set allEntries = standEntries |merge(premEntries) %}
{% set posts = craft.entries.id( allEntries ) %}
{% paginate posts.limit(12).orderby('Premium desc') as pageInfo, pageEntries %}
{% set pageCount = pageInfo.totalPages %}

    <div class="container-fluid greyouter {% if premCount <= 12 %}whiteouter{% endif %}">

                {% for entry in pageEntries %}

                    {% if pageInfo.currentPage != '1' %}

                    {% endif %}

        {% if pageInfo.currentPage == '1' and premCount == '0' %}

        {% endif %}

    {% if pageInfo.currentPage == limitRoundUp and loop.index == lim4 %}

{% endif %}

{% endfor %}

    {% include 'includes/_sect-pagination' %}


Garnish event when changing category group

Craft.elementIndex.on('selectSource', function(){
     alert('changed the source');
});

Craft.elementIndex contains the plugin for all index pages, that means all entries as well as users and categories. There is an updateElements event as well..
Here is a full list

afterInit
selectSource
selectSite
updateElements
selectionChange
enableElements
disableElements
afterAction


Dynamic asset subfolder path for Craft Commerce

If you have an Asset field outside of Matrix and you want to set its "Upload Location" to be a dynamic value of Dropdown field inside of a separate Matrix field, something like this should work:

{{ object.matrixFieldHandle.type('matribBlockHandleTheFieldLivesIn').first().dropdownFieldHandle.value }}


Get a specific entry by its index or number?

I don't know whether you've seen the batch Twig filter? You may find if useful to accomplish exactly what you are trying to do, but with a little bit less hassle.

From the example in the link above:

{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}

{% for row in items|batch(3, 'No item') %}

        {% for column in row %}
            {{ column }}
        {% endfor %}

{% endfor %}

And here's what it outputs:

        a
        b
        c

        d
        e
        f

        g
        No item
        No item

Essentially you're grouping your values into rows of a specific number (in this example it's 5). Then you can specify what to put in any empty spaces. So here it's the words 'No Item', but in your case it could be the middle partner entry.


Craft Commerce: How to manage different prices with one product?

Craft Commerce support has answered to my question :

  Currently Craft Commerce can not have a stock counter that covers more
  than one variant. The default product+variant system is not designed
  for tickets. We hope to see a ticket 'Purchasable' plugin in the
  future. You can request this feature here.

  If you have some plugin experience, you could get around this issue
  you described with a plugin that updates the stock of other variants
  when someone purchases a variant using the onOrderVariant event. You
  would likely need to know the relationships between SKUs for the
  different variants within your plugin, and deduct the stock from the
  related variants like so:

craft()->db->createCommand()->update('commerce_variants',
  ['stock' => new \CDbExpression('stock - :qty', [':qty' => $theQty ])],
  'id = :variantId',
  [':variantId' => $variantId]);

  Check out the Stock Notifier plugin as it matches closely to the
  events you would need to use.


The template engine (Twig) doesn't do anything like that – my guess is that the links only appear to render like your second example, because you're looking at the markup in your browser's dev tools, and modern browsers (e.g. Chrome) do a pretty good job of rendering invalid HTML.

Take a look at the raw source code (i.e. "View source" in your browser), and I suspect the actual rendered HTML will look exactly like your first example.

In any case, nesting <a> tags is not allowed and a very bad idea – so I'd recommend not doing it all :)


Passing params to Freeform’s `render` tag

That isn't possible right now, the things you can pass to the render tag are listed here under customAttributes.

We might, however, add such functionality in the future.


Freeform Element Connections to Update Existing Entries

According to the Freeform docs it looks like you'll need to pass an element ID.

Freeform allows you to edit/update existing Craft elements (Entries, Users and Calendar Events currently) by including the elementId parameter in your form. It works by feeding a Freeform form an element ID.

{{ craft.freeform.form("editCraftUsers").render({
    elementId: currentUser.id
}) }}

The docs have more details on the exact options.


Using Twig's replace filter with getURL()

Try using:

{{ gist.gistImage.first().getUrl('gistUnit')|replace({'http': 'https'}) }}


Front end authentication on an entry and its related entries

From experience, in terms of ui/ux AND ease in front end stages, If you can do things the other way round, do that.

So attached entries to users basically. When you have a new user, you add entries in one place vs adding the user on every single entries which, if you have loads of could turn into a bit of a mission.. You'll find this way round easier to maintain, in the front end, you can just access related entries through the currentUser very easily instead of going through entries.

This is my personal preference based on recent experience but I don't know how much flexibility you have in terms of development so it may not be possible for you.


How to apply a filter on a title with several concatenated elements?

I've tested these three methods (the first one from AbbeyDesign's answer,) and they seem to work fine with variables, I can't see any obvious reason why they wouldn't:

{% set entry = { artistFirstName: 'hello', title: 'world' } %}

{% set title = (entry.artistFirstName|capitalize) ~ ' ' ~ (entry.title|capitalize) %}
{% set title = "#{entry.artistFirstName|capitalize} #{entry.title|capitalize}" %}
{% set title = [entry.artistFirstName|capitalize, entry.title|capitalize]|join(' ') %}

Results in "Hello World" in each case.


Yep, you should definitely be able to do what you want.

What I do is I test the code in the actual Twig template used to display the page, and then once I have it working, I paste it into the SEOmatic field, and add object. in front of the entry.

e.g.: If this gives you the results you want in the template:

{{ entry.title }} | {{ entry.parent.title }} | Company Name

Then when you paste it into SEOmatic's CP fields, it'd look like this:

{{ object.entry.title }} | {{ object.entry.parent.title }} | Company Name

I find that this makes it easier to debug.


Searching multiple queries using CraftCMS search function

You'd have to set up an ElementCriteriaModel with parameters adapted to your entry type and the values you're getting from the query string.

I'd recommend to read the official docs on that topic

https://craftcms.com/docs/templating/elementcriteriamodel
https://craftcms.com/docs/templating/craft.entries

After that you shouldn't miss Combined searches and filters using Craft on Webstoemp's blog, a great introduction to setting up search forms and "filtering" the results with the ElementCriteriaModel.


Try using the relatedTo() filter as explained here:

http://buildwithcraft.com/help/entries-related-to-category

{% paginate craft.entries.section('products').relatedTo(requestCategory).limit(9) as entriesOnPage %}


UX issue with new email verification link

The only way I found to accomplish this was with a custom controller that essentially overrode actionVerifyEmail and _processTokenRequest from UsersController. (With a hook into email.onBeforeSendEmail to rewrite the verification {{link}} to use the custom controller action). It's fragile, but it works.

I've created a feature request to smooth out this experience:
https://github.com/craftcms/cms/issues/1228


Datagrab style plugin for importing CSV data to sections (Channels)

I'm not familiar with Datagrab, but from your description it sounds like the Import plugin might work for you.


not sure if it matters but in my config I have buttons in quotes

"buttons": ["format","bold","italic","underline","lists","link","file","image","horizontalrule"],


Why I can't upload a favicon.ico as an Asset?

1) It's not allowed because it's currently not in the allowedFileExtensions config setting.

2) Just add 'ico' to the extraAllowedFileExtensions config setting and you'll be able to upload .ico file.


If you change your query and sort by ascending postdate, it will start with the oldest and end with the newest:

    {% set entriesInYear = craft.entries.section('blog').limit(null).after(year).before(year+1).order('postDate asc') %}


How to set simple yes/no checkbox using Freeform

I don't think this has anything to do with your code, and actually appears to be a bug in Freeform itself, where the Submission object and email notifications are showing the value as whatever the default is set to.

I've made a note about this issue and we'll have it corrected shortly. :)


Show error when normal user try to login in CP

You are seeing this because you have 'devMode' => true, in your config/general try switching to false and should hit a 'user friendly' message


Update: temp fix
as per comments below i fixed with js plugin https://github.com/lindseydiloreto/craft-cpjs

Rough and ready hack to only run extra js when editing arabic entry.
On CpjsPlugin.php I edited the bottom:

 private function _renderJs()
 {
    $settings = $this->getSettings();
    if (trim($settings->jsFile)) {
        $filepath = craft()->config->parseEnvironmentString($settings->jsFile);
        if ($hash = @sha1_file($filepath)) {
            craft()->templates->includeJsFile($filepath.'?e='.$hash);
        } else {
            craft()->templates->includeJsFile($filepath);
        }
    }
    //joomkit hack for arabic redactor  fix
    $lang =  $this->_getCurrentLocale();
    //only add extra js if arabic is set in url
    if($lang == "ar"){
        craft()->templates->includeJs($settings->additionalJs);
    }
}

private function _getCurrentLocale() {

    $segments = craft()->request->segments;
    $lastSegment = end($segments);

    return $lastSegment;

}

The the extra js settings;

$(function()
{
$('.redactor-editor>*').css({
    direction: 'rtl',
    float: 'right'
});
$('.input #title').css({
    direction: 'rtl',
    float: 'right'
});

});

this will help arabic translators start translating hopefully


Does Craft Commerce support One Time Password and Social Login features?

Craft Pro gives you the ability to add multiple user accounts to your site. Craft Commerce is a plugin that extends Craft so user accounts and everything that goes with them are available to use.

There is a plugin to enable social logins (currently in beta) made by Dukt that you may find helpful.


You could use the Control Panel CSS plugin that lets you add arbitrary css to the control panel.

Then you could target all redactor fields like so:

.redactor-layer * {
    font-family: 'Arial';
}

EDIT slightly more troubling is that you are getting Trebuchet in the first place, it should be Arial anyway.

UPDATE it turns out this change came about in a recent Craft update (2.6.2963) that updated Redactor II from 1.3.2 to 2.2. My best guess is that it crept in to the Redactor II 2.0 release, which also included the change to the toolbar icons.


Get user data in Craft CMS Personal edition

Should be possible with a simple plugin that registers its own Twig extension.  Head over to https://pluginfactory.io/ and check the "Twig Extensions" option to have it generate the boilerplate code for you.

100% untested, but in your PluginNameTwigExtension.php file, add a getGlobals() method that does something like this:

public function getGlobals()
{
    $criteria = craft()->elements->getCriteria(ElementType::User);
    $criteria->admin = true;
    $user = $criteria->first();

    return array('adminAccount' => $user);
}

Then every template should have a global adminAccount variable available to it that's a UserModel object, so you can do things like {{ adminAccount.firstName }}.


The key to this is to use the |kebab filter and the relatedTo params.

Listing:

{% for tag in relatedTags %}

{{ tag.title }}

{% endfor %}

Fetch related articles

{% set tag = craft.tags.search(craft.request.getSegment(4)) %}

{% for entry in craft.entries.relatedTo({ targetElement: tag[0], field: tagField }) %}

The tag[0] is necessary, as {{ craft.tags.search() }} will return an array (even if there's only one tag returned).

This finds entries that are specifically related to Two Words (a tag object, pulled from the URL), and searches in the tagField specified.

The alternative to the above is to use {{ tag.id }} and {{ craft.tags.id() }}, but that isn't URL/SEO friendly.


Upgrading from v2 to v3 results in internal server errors

After doing some more digging in storage/logs, it turns out that the permissions were incorrect on the "cpresources" director. Once I fixed those, the upgrade progressed as normal.


I think you can use this:

{% for field in entry.subentry[0].getFieldLayout().getFields() %}
    {{ field.getField().name }} {# or .handle #}
{% endfor %}

You might try a great little plugin called inspector that prints out all of the attributes and methods of an object using either filter {{ entry.subentry|inspect }} or method {{ inspect(entry.subentry) }} syntax. Its output is a little cleaner than dump, and nice for following the rabbit-hole.


Entries object getting reset after a relatedTo query

Based on the bug report found here (https://github.com/craftcms/cms/issues/2160), I am now creating a variable that contains all of the items prior to filtering it.

{% set entries = craft.entries.type('publications').orderBy("postDate desc") %}
{% set allEntries = entries.all() %}

I can then use entries to filter through the available categories and then use allEntries to loop through all of them.

I understand I could also have used clone() to get a copy to work from in my category loop.

{% set catEntries = clone(entries).relatedTo(cat) %}


Redactor ImagePosition - no custom styles

I was being a dummy. It works and does what it's meant to.

I just thought you could make your own drop parameters and classes.

You can only change the classes added, the "left, center, right" are not editable.


Why does asset uploading fail with the error "Uploaded file was empty"?

You'll get that message whenever Craft/PHP can't upload the file (for any number of reasons).

Looks like you've covered permissions and some common php.ini environmental limitations.

If it's happening of every file regardless of file type or size, you can probably rule out any GD or Imagick related bug.

Other things to check for:

You're out of disk space on your hosting account.
You're out of allocated space for the /tmp folder on your account.
There is some firewall / .htaccess rewrite rule / Suhosin / mod_security blocking the request.

It's probably worth checking craft/storage/runtime/logs for any errors as well as your web server's error logs.


How to call two separate images from Matrix field

I think the issue here where you are setting your image variable.

{% set image = block.image.first() %}

This should reference the field handle of the asset you are trying to get the url of, so it should be this instead:

{% set image = block.firstImage.first() %}

Then where you try and display the image it should be:

You would then need to update this for the secondImage.

It might be worth mentioning that there is a cleaner way to achieve what you’re after, with just one asset field.

You can upload multiple images to a single asset field, so assuming firstImage has two assets attached, your code could be shortened to the following:

...
{% elseif block.type == "imageDouble" %}

 {# this has two assets attached #}
 {% set images = block.firstImage %}

 {% if images and images|length %}

    {# Loop through the images #}
    {% for image in images %}

    {% endfor %}

 {% endif %}

{% endif %}
...

This will help keep your code from repetition and will be easier to maintain in the future :)


Query only Tags wich are not connected to a revision

I found the solution and posted it here in another issue related to this problem.
Here is my solution (just the code):
$query = (new Query())
    ->select([
        '{{relations}}.targetId as id',
        'COUNT({{relations.targetId}}) as count',
        '{{content}}.title as title'
    ])
    ->from('relations')
    ->leftJoin('tags', '{{relations}}.targetId={{tags}}.id')
    ->leftJoin('content', '{{content}}.elementId={{tags}}.id')
    ->leftJoin('elements', '{{elements}}.id={{tags}}.id')
    ->leftJoin('elements source', '{{source}}.id={{relations}}.sourceId')
    ->where([
        '{{elements}}.enabled' => 1,
        '{{source}}.enabled' => 1,
        '{{source}}.revisionId' => NULL,
        '{{source}}.draftId' => NULL,
    ])
    ->groupBy('id, title')
    ->orderBy( 'count DESC, title ASC')
;

$query->limit($limit);

if (is_numeric($limit) && !is_null($limit)) {
    $query->limit($limit);
}

$results = $query->all();

foreach ($results as $key => $value) {
    $id = $value['id'];
    $results[$key] = Tag::find()->id($id)->one();
}

return $results;


Is it possible to change the time increments in the Date/Time field?

Not currently, but it should probably be a setting on the field.

Craft currently uses jquery.timepicker (in craft/app/resources/lib/jquery.timepicker/jquery.timepicker.js) and is just going with it's default step: 30.

I'll add it to “The List”™.


Internal Server Error for admin login and dashboard

To get some ideas we'll need more information. I suggest

Go to storage/logs folder
Hit from that directory tail -f *
Then go to your chrome and try to access your : admin page
Go back to your tail -f you will see some error

Tell us more about the error your find.


Calculating a score based on a drop down field value

When working with a dropdown in Twig, it's important to remember that you're dealing with an object (not a simple string).

This is an object:
{{ entry.myDropdown }}

It's easy to forget, however, because Craft works a little magic behind the scenes. There are many objects (including this one) which have an internal __toString behavior. This is called a "magic method", because it will automatically convert the value to a string when you use it as a string.

But in your case, you're not directly outputting it as a string. You're trying to do math with the object, and the object isn't really sure how to respond to that. So nothing gets converted, and your object remains mathematically useless.

Instead, you'll need to append .value to your object. This will give you the selected value of your dropdown, in a format that you can use.

This is the dropdown's selected value:
{{ entry.myDropdown.value }}


Craft 2: possible to control plugin triggering order?

Unfortunately, nothing I'm aware of for Craft 2, I'm afraid.
In Craft 3, there's still not a great solution, but there is a $append parameter where you can kind of force it to go to the top of the list: https://github.com/yiisoft/yii2/blob/master/framework/base/Event.php#L103
But that would stop a plugin that was loaded after yours to use the same parameter and come out on top.


Is there a way to delete all entries in a section?

If you delete the section, that will delete all the entries in the section as well.


Is it possible to have category listing page of entries if the category is defined within a matrix block inside said entries?

First you need to define the category. If your category group has the “Categories in this group have their own URLs” checkbox checked, and the URL Format is set to category/{slug}, and this is happening on the template you’ve specified in the Category Template setting, then all the stars have aligned and this step is taken care of for you automatically. The category will already be available to your template, and it will be called category.

Otherwise you will have to fetch it yourself:

{% set category = craft.categories({
    group: 'workCategories',
    slug: craft.request.getSegment(2)
}).first() %}

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

Once you have your category, you can fetch the related Clients using the relatedTo param on a craft.entries query:

{% set clients = craft.entries({
    section: 'clients',
    relatedTo: {
        targetElement: category,
        field: 'workSamples.myCategoriesField'
    }
}) %}

That’s saying: “Give me the entries in the clients channel, which are related to category (where category is the target of the relation), via the myCategoriesField sub-field of a workSamples Matrix field.” Make sense?

Once you have those client entries you can loop through them, and show their respective Matrix blocks which are related to the category:

{% for client in clients %}

{{ client.title }}

    {% for workSample in client.workSamples.relatedTo({ targetElement: category }) %}
        {% for image in workSample.myAssetsField %}

        {% endfor %}

        {% for row in workSample.myTableField %}
            {{ row.youtubeId }}
        {% endfor %}
    {% endfor %}
{% endfor %}

If there are going to be a lot of clients/Matrix blocks/assets getting looped through, it’s probably going to be a good idea to wrap the whole thing in {% cache %}...{% endcache %} tags, as there’s potential for the query count to really pile up here.


Craft Commerce is a young product and as such, there are indeed limited options for third party plugins.

Good news, though - writing a shipping plugin at least is not difficult (well, the Commerce part isn't - the API of the shipping service is of course, up to that shipping service!). See https://craftcommerce.com/docs/shipping-methods to get started.  I've personally written a live rates plugin (for TNT) and several unique table based ones, and I've found the process easy and clean.

There is already a ShipStation plugin - https://onedesigncompany.com/craft-cms/plugins/oneshipstation - and ShipStation handles UPS, FedEx etc.

On tax, I don't know a lot about that and so far I think Commerce's tax support is a little limited (e.g. no tax on shipping support).

Fortunately, Craft/Commerce support is excellent and if you do need to integrate a new service, you'll fine Luke Holder and the rest of the Craft team are very helpful with that sort of thing - and of course they're keen to see the Craft/Commerce eco-system grow.  support@craftcommerce.com is the address you need :)


Redactor - formattingAdd isn't changing code

Try this for data attributes:

"formattingAdd": {
    "add-animate": {
        "title": "Animate",
        "api": "module.block.format",
        "args": {
            "tag": "p",
            "attr": {
                "data-aos": "fade-right"
            },
            "type": "toggle"
        }
    }
}

This for classes:

"formattingAdd": {
    "add-note": {
        "title": "Note",
        "api": "module.block.format",
        "args": {
            "tag": "p",
            "class": "note"
        }
    }
}

redactor settings formatting


Looping Related Entries with a Super Table

The issue is: you don't really loop your entries at all.

{# get all super table rows #}
{% set superTableRows = block.related.all %}

{% if superTableRows is not empty %}

            {# loop all of your super tables #}
            {% for row in superTableRows %}

                {# loop all contentEntries in each row #}
                {% for entry in row.contentEntry.all() %}

                    {#
                        display the alternative title set in your supertablerow
                        and if thats not set display the entries title
                    #}
                    {{ row.altTitle?? entry.title }}

                    {# same as above #}
                    {{ row.altDescription ?? entry.previewDescription }}

                {% endfor %}
            {% endfor %}

{% endif %}

block.related is an Object of type ElementQuery. block.related.altDescription returns the criteria of this Query, this is mostly empty since no criteria is set by default.


Is it possible to run Craft CMS with putenv() function disabled?

DotEnv only calls putenv if it sees the function is available since version 2.4.0, so make sure you're running at least that: https://github.com/vlucas/phpdotenv/commit/58633a061610ffd731d7fbbc8f7f009d14b2e4cf

Even then, I'm pretty sure other Craft dependencies (like Composer) will still require putenv support.


FeedMe for Craft 3: Tweaking attribute values from feed before FeedMe process it

Have you tried EVENT_AFTER_PARSE_FIELD https://github.com/craftcms/feed-me/issues/516

use yii\base\Event;
use craft\feedme\services\Fields;
use craft\feedme\events\FieldEvent;

Event::on(Fields::class, Fields::EVENT_AFTER_PARSE_FIELD, function(FieldEvent $event) {
    if ($event->fieldHandle === 'myAssetsField' && $event->fieldValue !== null) {
        // $event->fieldValue will be an array of assets (already saved).
        // Modify the assets or the field value as needed...
    }
});


Invalidating the cache tag from a plugin?

The TemplateCacheService provides a ton of helpful methods to take care of this for you.

While you can explicitly tell Craft to invalidate certain caches (by element ID, etc.) if you need to, I prefer to use includeCriteriaInTemplateCaches() and includeElementInTemplateCaches() to register the appropriate element(s)/criteria with the template cache, so that Craft takes care of cache invalidation according to its own internal logic:

$myCrtieria = ... ; // (some ElementCriteriaModel)

$cacheService = craft()->getComponent('templateCache', false);

if ($cacheService)
{
    $cacheService->includeCriteriaInTemplateCaches($myCriteria);
}

...

p.s. Unless you really need to render HTML via a Twig hook, I strongly suggest refactoring to use a custom Template Variable instead. Doing so is more consistent with Craft's own internal practice. Twig hooks are typically used to change context variables and perform other logic that is specific to changing how Twig renders templates. For doing content-related business logic (e.g. fetching data from the database and rendering it into templates), using Craft's provided structures will save you trouble down the road.


Customize markup of email select field in Sprout Forms

This feature has been added in Sprout Fields v2.1.0

You can now use the Email Select field via custom HTML and obfuscate email addresses. I've added an example in the docs:

{% set contact = craft.sproutForms.form('contact') %}

{% set emailSelectField = contact.getField('emailSelect') %}

<select name="fields[{{ emailSelectField.handle }}]">

  {% set value = contact is defined ? contact.emailSelect.value : null %}

  {% set options = craft.sproutFields.obfuscateEmailAddresses(emailSelectField.settings.options, value) %}

  {% for option in options %}

    {% if value != "" %}
      {% set selected = (option.selected == 1) ? true : false %}
    {% else %}
      {% set selected = (option.default == 1) ? true : false %}
    {% endif %}

    <option value="{{ option.value }}" {% if selected %}selected{% endif %}>{{ option.label }}</option>

  {% endfor %}

</select>


All of the references in the source key were missing from my old installed.json file.

I'm not entirely sure what caused the issue but I corrected by installing a new instance of Craft and copying the installed.json into the version of the file that was causing problems.

I am now able to run composer commands again.


How to model a multiple relation situation?

I think this is the best way to model the data, and it lends itself very well to how Craft work.

I guess the only reason to go with the Matrix approach instead, would be to ease how the information is published in the control panel. In some cases it might be easier to just publish one question with all the answers, instead of one question and all the answers seperately. But it's hard to say, not knowing the actual content and amount of data.

It would definitely be possible to go for the Matrix solution too, but it might be a bit more complex to use in your templates, and maybe less efficient. But again, depends on your actual case.


Missing Download PDF Button in Orders for Craft Commerce

The Download PDF button will show if the OrderModel that gets passed to the template's getPdfUrl() method returns a URL.

You can see the logic it uses in commerce/models/Commerce_OrderModel.php, function getPdfUrl().

It gets the orderPdfPath Commerce setting, then checks if that template exists on the front-end templates folder.

My guess is you've got something messed up with the path to that template somewhere.


You should be using {{currentUser.id}} instead of {currentUser.id}

The difference is that double curly brace syntax works on the global scope, while single curly brace syntax tries to resolve itself on the current element. Relevant documentation.


If your domain name is actually staging.somedomain.com and your multi-environment config is searching for stage., then they won't match up.

What will match, however, is the .com key directly underneath it, which is probably what you're thinking is only for the live site.

Being more explicit with your matching multi-environment config keys will probably clear up the confusion.


You likely won't need to write a plugin at all – you can easily create different user groups (e.g. "Workers" and "Clients") from the Control Panel, and grant those groups different permissions. An example of a permission is "Access the CP". The user group permissions will be automatically applied to any new users added to the group.

To create a user group, visit Settings -> Users in the CP. The edit form for a user group will have a plethora of checkboxes for every possible permission. Note that when checked, many of these checkboxes will actually reveal even more checkboxes, for even more fine grained control over permissions.


It is indeed possible. Craft has a handy general configuration option for this exact situation.

return array(

    'backupDbOnUpdate' => false

);

Just add that to config/general.php and that should do the trick!


Is it possible to route a subdomain to specific template group?

For this example we have two domains:

http://www.example.com
http://subdomain.example.com

To use different templates for the subdomain, we can accomplished this with these steps:

1) Setup subdomain to point to a different directory on your server:

Domain: /home/wherever/public_html
Sub-domain: /home/wherever/public_html_subdomain

2) Copy your index.php file over to your new subdomain directory and update the CRAFT_TEMPLATES_PATH variable to point to the location you want to have your templates.  In this example, both template folders are above web root.

// index.php for domain
define('CRAFT_TEMPLATES_PATH', realpath(dirname(__FILE__) . "/../templates").'/');

// index.php for subdomain
define('CRAFT_TEMPLATES_PATH', realpath(dirname(__FILE__) . "/../templates_subdomain").'/');

Your template folders now look like:

/home/wherever/public_html
/home/wherever/public_html_subdomain
/home/wherever/templates
/home/wherever/templates_subdomain


Craft 2, MySQL database, Twig, JavaScript files

I have all ready created form, for parents profile that has child info. On website i need to add dropdown menu, in which is information of there children, so parents when is log on website, don't need to fill out information for children, they can choose from dropdown.

It sounds like you want to loop through the children (Entries?) and output the data as a dropdown menu...

{% set children = craft.entries.section('children').all() %}

<select name="fields[children]">
    {% for child in children %}
        <option value="{{ child.id }}">{{ child.title }}</option>
    {% endfor %}
</select>

For more information, see this thread...


How do I wire my form action to my controller action?

I had the plugin set up correctly but I didn't go into the administration menu and install the plugin via the GUI.


Getting all content, including Matrix fields from an EntryModel

ContentModel will only have the values in the actual content table, and the values that are actually there still may not be what you’re after, because accessing those values directly won’t give the field types a chance to do any preprocessing on their data.

So the best way to reliably get an array of all of an element’s custom field content is to go through its Field Layout, via BaseElementModel::getFieldLayout():

$values = array();

foreach ($element->getFieldLayout()->getFields() as $fieldLayoutField)
{
    // $fieldLayoutField is a FieldLayoutFieldModel, *not* a FieldModel
    // http://buildwithcraft.com/classreference/models/FieldLayoutFieldModel
    // so get the actual FieldModel here
    $field = $fieldLayoutField->getField();

    // Now get the prepped field value
    $value = $element->getFieldValue($field->handle);

    $values[$field->handle] = $value;
}


Separate cache per user or user group in Blitz cache

No, it is not possible to store different versions of cached pages. Your best bet would be to use the dynamic content feature that Blitz provides for injecting the content that can vary based on the user into the cached page.


How can I add custom field to order by on the admin CP in Craft 3?

You can take a look at this question Set custom sort order for index pages in the CP? for Craft 2 and see updating Plugins for Craft 3 in the docs

// Old:
public function modifyEntrySortableAttributes(&$attributes)
{
    $attributes['id'] = Craft::t('ID');
}

// New:
use craft\base\Element;
use craft\elements\Entry;
use craft\events\RegisterElementSortOptionsEvent;
use yii\base\Event;

Event::on(Entry::class, Element::EVENT_REGISTER_SORT_OPTIONS, function(RegisterElementSortOptionsEvent $event) {
    $event->sortOptions['id'] = \Craft::t('app', 'ID');
});

Keep in mind your field must be sortable via SQL


Applying project config changes with post-receive git hook

Based on your comment that you get an error saying Craft is not installed, to me that suggests the bash script does not have access to your environment variables, (this can also be a problem when running cron jobs).

To remedy this, create an env text file to export all the same values as those in your production env variables. For this example name it something like .env_cli.txt and save it in your site in the same place as .env-example if you have one. Add it to your .gitignore too. Syntax should look something like this:

export ENVIRONMENT="live"
export SITE_URL="https://www.example.com"
export DB_DRIVER="mysql"
export DB_SERVER="123.456.789.10"
export DB_USER="aaa"
export DB_PASSWORD="bbb"
export DB_DATABASE="ccc"
export SECURITY_KEY="ddd"
export DB_TABLE_PREFIX="craft_"
export SOME_CUSTOM_VAR_YOU_MIGHT_HAVE="something"

Then in your git hook, you can use a leading . to "source" that env file (basically meaning to suck in and consume all those exported vars), and then run your command(s) afterwards like this:

. /path/to/your/env-file/.env_cli.txt && /path/to/craft/./craft project-config/sync && /path/to/craft/./craft clear-caches/all && /path/to/craft/composer update

You could of course stick with relative paths to make it shorter, I just tend to use absolute paths for more certainty.


Logging out users - logoutPath & logoutUrl

Might be going overboard, but you could have a plugin with it's own controller that provided different logout behavior.

But it sounds like to me what you're looking for is something like a 'logoutRedirect' config setting.  Probably worth adding to the feedback site!


The value you need to set the postDate parameter to is quite complex. If you define a dedicated variable for it, it makes the code more readable and you can more easily debug the value using the dump() function.

For the problem itself, you were on the right track. The main problem is a syntax mistake, you are passing in the 'and', '>= ', ... values without wrapping them as an array.

Some other changes I’d suggest is to use the < operator in combination with a relative time of 'first day of next month', so every entry before 00:00 of that day (see documentation of relative date/time formats).

And instead of the .date property, I'd rather use the date filter to output the DateTime object as a string in the right format. Which can be 'Y-m-d' to omit the time completely (Craft sets it back to 00:00), or one of the characters that output a full date with time 'c' or 'U' (see documentation of date format parameter).

{% set firstDay = date(year ~ '-' ~ month ~ '-01') %}
{% set lastDay = firstDay|date_modify('first day of next month') %}

{% set postDateParam = ['and', '>= ' ~ firstDay|date('c'), '< ' ~ lastDay|date('c')] %}

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

{% set archive = craft.entries({
    section: 'blog',
    postDate: postDateParam,
}) %}


Example of Craft 3.0 plugin - querying an existing table

A great place to start with this is over on https://pluginfactory.io/.

Select "Craft CMS Plugin Version 3.x" and check any plugin components you'd like to include, and it will build out the plugin scaffolding for you with ample comments and some examples.

For accessing database content, Craft heavily relies on the framework it uses, Yii 2.  The "Working with Databases" docs are a good place to start: https://www.yiiframework.com/doc/guide/2.0/en/start-databases#working-with-databases

It will go over how to retrieve data using Active Record (Craft's AR classes) and Query Builder for direct database access.

You can do that data access from your plugin's Variable class, but a more common pattern is for the Variable class to have a wrapper method that calls a Service class method that returns the value to the Variable, then back to the template.

You can see Craft's Service classes here: https://github.com/craftcms/cms/tree/develop/src/services

And in case it's not obvious yet, the Craft source code itself is a great place to look for examples of how to do things in your plugin.


How can I make the redactor table plugin show extened options?

I don't think the features you're asking for are possible with the default Redactor Table plugin Craft comes with, and as far as I know, it is also the only table plugin for Redactor out there.


Adjusting Max File Size - Stuck at 16M After Adjusting general.php

My guess is that your php upload_max_filesize is set to 16M, you'll need to adjust that.


I have a table type field that I need to access to rows individually

{{ entry.myTableField[1] }} and {{ entry.myTableField[6] }}

You also might want to check to make sure they exist.

{% if entry.myTableField[1] is defined and entry.myTableField[1] is not empty %}
     {{entry.myTableField[1]}}
{% endif %}


Adding php.ini file to root crashes site

Checkout a few different log files to see if they can help out.

craft/storage/logs/phperrors.log
If you're running apache, the apache log files
If you're running php on ngix or apache, the php log files


Is it possible to bulk-edit a field across multiple entries at once?

This plugin does it for Craft 3: https://github.com/kffein/craft-bulk-edit


Plugin removed, can't get rid of its data | Control Panel JS

Assuming that you entered your explosive JavaScript directly into the control panel (as opposed to an external file), the answer is... complicated.*

  * Disclaimer: I am not a Project Config expert. This advice has not been thoroughly tested. Please tread carefully when editing your database and/or project.yaml file.

If you're using Project Config, you'll want to update the value stored in your config/project.yaml file. Once you've done that, run ./craft project-config/sync to update your database accordingly.

If you're not using Project Config, then you should be able to just update the database directly. Go to the projectconfig table and change this row...

|  plugins.cp-js.settings.additionalJs  |  (your explosive js)  |

For reference, here's a flowchart to illustrate how the data gets saved...


How are changes to the dashboard scoped?

Every user has their own unique dashboard. The changes you make to your dashboard affect only your account.

It cannot be shared, and it cannot be preset in any way. It is not related to user groups at all. The only way to change someone else's dashboard is by logging into the control panel as an admin, then finding that user and "Log in as them".

There have been a handful of feature requests regarding pre-setting dashboards, or remotely controlling or locking another user's dashboard... but for the near future, this is simply how dashboards work.


Digging around a bit, it looks like more complex order queries need to be fully elaborated. I adjusted as follows for it to work:
orderBy : "DATEDIFF(`content`.`field_screeningDateFirst`, `content`.`field_screeningDateLast`) DESC",


Commerce 1 create a new order programmatically

To add orders programmatically, you can do so by using the Commerce_OrderModel class.

Like so:

$order = new Commerce_OrderModel();
$order->email = 'test@example.com';

// Add your products here and other order info...
// .................

$success = craft()->commerce_orders->saveOrder($order);


This ended up being because not all categories were properly resaved after a new locale was added. Resaving the categories solved it.


How do I set up Craft 3 to web server in WAMP?

I only know mamp. You have to point the local domain to the web folder. If you don't change the folder structure the composer libraries will live outside the public folder just fine.

Do you get any errors or something?


Use different template for same route based on user group

Just do it with Twig by having a main template pull from two other templates based on the user group. So in your index template (or whatever template gets called), just add this at the top:

{% if currentUser.isInGroup('customer') %}
    {% include '_dashboard/customer/settings' %}
{% else %}
    {% include '_dashboard/admin/settings' %}
{% endif %}

And then fill out each template however you want.

Conversely, you can check if the user is a CMS admin with {% if currentUser.admin %} and then the {% else %} would be for customers.


Searching a specific section by four different types of parameters?

One method is to build your params before performing the search.

{# set base params #}
{% set params = {
    section: 'portfolio',
    limit: null
} %}
{% set relatedParams = ['and'] %}

{# status #}
{% if craft.request.getParam('status') %}
    {% set status = craft.request.getParam('status') %}
    {% set params = params|merge({'companyStatus':status}) %}
{% endif %}

{# industry #}
{% if craft.request.getParam('industry') %}
    {% set category = craft.categories.group('industries').slug(craft.request.getParam('industry')).first %}
    {% set relatedParams = relatedParams|merge([{ targetElement:category }]) %}
{% endif %}

{# board member #}
{% if craft.request.getParam('boardMember') %}
    {% set boardMember = craft.entries.section('team').slug(craft.request.getParam('boardMember')).first %}
    {% set relatedParams = relatedParams|merge([{ targetElement:boardMember }]) %}
{% endif %}

{# add relatedParams to params #}
{% if relatedParams|length > 1 %}
    {% set params = params|merge({'relatedTo':relatedParams}) %}
{% endif %}

{# perform search #}
{% set searchParams = craft.request.getParam('q') %}
{% set entries = craft.entries(params).search(searchParams|trim) %}

{# display results #}
{% for entry in entries %}
    {{ entry.title }}
    ...
{% endfor %}

To AJAX load results you would place this in another template and load it dynamically with jquery. See this answer for an example.

To paginate the results you will need to submit your form as "GET" and append the query to your nextPage and prevPage links. See this answer for an example.


Sounds like you're on the right path. Create a Global matrix field containing an asset field for Social Icon, a text field for Social Url, and a lightswitch field for Enabled/Disabled. Then the user can add new social media icons as needed and manipulate the url.


Plugin CKEditor outputs something with nothing?

This has been fixed in the master branch, but not yet tagged in a release: https://github.com/craftcms/ckeditor/pull/6

Until it's tagged, you won't be able to get that fix in from the Plugin Store, but you can pull it in with Composer in the command line if you want.

FWIW, it's currently a pretty minimal beta version of the plugin using an older dev preview version of CKEditor 5, so I wouldn't rely on it too heavily until it gets updated.


There are several config settings which should help...

maxInvalidLogins - The number of invalid login attempts Craft will allow within the specified duration before the account gets locked.
invalidLoginWindowDuration - The amount of time to track invalid login attempts for a user, for determining if Craft should lock an account.
cooldownDuration - The amount of time a user must wait before re-attempting to log in after their account is locked due to too many failed login attempts.

In addition, you may also want to change your cpTrigger from the default.

Lastly, there is a feature request to strengthen password requirements, where Brandon Kelly posted a link on how to enforce your own stricter password requirements.


Trying to launch Craft CMS site on 1&1.co.uk and told I don't have permission. Any help why?

It's likely a problem with permissions on your folders. You can find the right permissions here: https://craftcms.com/docs/installing#step-2-set-the-permissions


How do I pass dynamic year and month to the .after() and .before() functions?

In Twig, you concatenate strings with the ~ operator. So, if year and month are variables in your template, you can create a string in the required format like this

{% set yearMonth = year ~ '-' ~ month %}


Output tags in the order they were added to an entry

I managed to solve this by defining the tags as a ElementCriteriaModel. Instead of using the code above I used the following:

{% set tags = entry.tagsFieldHandle %}

{% if tags | length %}
   {% for tag in tags %}
      <li>{{ tag }}</li>
   {% endfor %}
{% endif %}

Explained further in the Tag section in the docs. {% set tags = entry.tagsFieldHandle %} is a shortcut for:

{% set tags = craft.tags({
   relatedTo: { sourceElement: entry, field: "tagsFieldHandle" },
   order:     "sortOrder",
   limit:     null
}) %}

This meant I didn't need to define the entry relation as the model does that be default and it also sorted the tags as they were defined in the entry with the "sortOrder" (which is also default).


How to include and use native imagemagick on server in Craft?

If you want to work with PECL imagick, which is the PHP wrapper for the ImageMagick library, then this should work:

$im = new \Imagick();

It's not namespaced, so it exists in the global namespace, which is what the \ does for you.


Config option to disable update capability per environment

I believe you're looking for the 'allowAutoUpdates' config option combined with multi-environment configs.


Merge related entries from several matrix blocks while maintaining other matrix field data

Figured it out:

{% for member in allMembers %}
    {% set cat = entry.featuredMembers.relatedTo(member).first() %}
    {{ member.categoryName }}
{% endfor %}


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

You can set the CP asset as depency then it will be loaded after it

{% do view.registerJsFile("<CDN_URL>",{
    depends: 'craft\\web\\assets\\cp\\CpAsset',
    position:3
}) %}

That's because Yii2 will always register Bundles without any dependencies first / in the order they are defined. If you require the CpAsset it will be loaded afterwards


It sort of depends on what information you have to identify the entry. If your external service knows the entry id that would be the most direct — otherwise you would have to find the entry by some other unique property.

To update an entry (given $entryId, $newTitle):

$entry = craft()->entries->getEntryById($entryId);
if ($entry) {
    $entry->getContent()->setAttributes(array(
        'title' => $newTitle
    ));
    craft()->entries->saveEntry($entry);
}

To update an entry (given $sectionHandle, $title, and $newTitle - or other unique property):

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = $sectionHandle;
$criteria->title = $title;
$entries = craft()->elements->findElements($criteria);

foreach ($entries as $entry) {
    $entry->getContent()->setAttributes(array(
        'title' => $newTitle
    ));
    craft()->entries->saveEntry($entry);
}

Could also use the 'search' method (although less reliable):

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->search = 'fieldHandle:searchstring';

In the last two cases, would need to handle the possibility that more than 1 entry is returned.

Also, when creating entries might want to include the authorId and typeId, in addition to sectionId:

$entry = new EntryModel();
$entry->sectionId  = $sectionId
$entry->typeId     = $typeId
$entry->authorId   = $authorId;
$entry->enabled    = true;
$entry->getContent()->setAttributes(array(
    'title' => $title
));
craft()->entries->saveEntry($entry);


How to target first or last item in a nav children loop

Update Sorry, I originally thought you were building nav and just showing simplified code. If you just want to list the categories then this should work:

{% nav category in categories %}
    {{- category.title -}}
    {% if not loop.last %}, {% endif %}
    {% children %}
{% endnav %}

If your trying to build a nav system, then this should work. In either case just place your 'loop' before the children tag. See this answer for another example.

    {% nav category in categories %}

        {% if loop.first %}

        {% elseif loop.last %}

        {% else %}

        {% endif %}

            {{ category.title }}
            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

    {% endnav %}


Disregard -- this was directly addressed by the 2.6.3015 update that was just released. The message no longer appears.


Two Domains. One Repo. Need Second License

You can set the CRAFT_CONFIG_PATH PHP constant on a per site basis so each of the sites will get their own craft/config folder (and therefore their own license.key files).


Get the Top Authors based on entry counts?

Here's how I did something similar, now edited the code for you to work with users. The better approach would be to do this with a plugin, because, as you can imagine, the only way doing this with Twig will end up in lots of DB queries, so please make sure to use the cache tag with this:

{# Build an associative array of user IDs to the count of related entries #}
{% set userData = [] %}

{# Go through all users #}
{% for user in craft.users %}

    {# Get total number of entries this user is the author of #}
    {% set count = craft.entries.authorId(user.id).total() %}

    {# Save entries count and ALL user data we gonna use to our array #}
    {% set userData = userData|merge([{ entriesCount: count, userId: user.id, userName: user.name }]) %}

{% endfor %}

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

{# Print the top 10 list #}
{% for element in userData %}
    <li>{{ element.userName }} ({{ element.entriesCount }} entries)</li>
{% endfor %}


Is there a way to output certain rows (or filter) from a table?

Since there are a set number of quarters you can probably just collect the entries in a temporary array. Then use those to build your tables.

{% set quarter1 = [] %}
{% set quarter2 = [] %}
{% set quarter3 = [] %}

{% for row in entry.courses %}

    {% if row.classQuarter == 1 %}
        {% set quarter1 = quarter1|merge([row]) %}
    {% endif %}

    {% if row.classQuarter == 2 %}
        {% set quarter2 = quarter2|merge([row]) %}
    {% endif %}

    {% if row.classQuarter == 3 %}
        {% set quarter3 = quarter3|merge([row]) %}
    {% endif %}

{% endfor %}

    {% for row in quarter1 %}

            {{ row.courseNumber }}
            {{ row.courseDescription }}

    {% endfor %}

    {% for row in quarter2 %}

            {{ row.courseNumber }}
            {{ row.courseDescription }}

    {% endfor %}

    {% for row in quarter3 %}

            {{ row.courseNumber }}
            {{ row.courseDescription }}

    {% endfor %}

You could also add an 'if' clause in the 'for...in' loop. See the twig docs on adding a condition for more info.

    {% for row in entry.courses if row.classQuarter == 1 %}

            {{ row.courseNumber }}
            {{ row.courseDescription }}

    {% endfor %}

    {% for row in entry.courses if row.classQuarter == 2 %}

            {{ row.courseNumber }}
            {{ row.courseDescription }}

    {% endfor %}

    {% for row in entry.courses if row.classQuarter == 3 %}

            {{ row.courseNumber }}
            {{ row.courseDescription }}

    {% endfor %}

And could also probably condense that using the range shortcut.

{% for quarter in 1..4 %}

        {% for row in entry.courses if row.classQuarter == quarter %}

                {{ row.courseNumber }}
                {{ row.courseDescription }}

        {% endfor %}

{% endfor %}


Is it possible to remove an entry's Expiration Date?

You could just empty the expiration date and time field and save the entry. Or do you want to do it in a plugin (using PHP)?


Doesn't the Expanded Singles plugin do what you're looking for? Best of luck.


I would definitely not rely on client-side validation. It's fine to do it from a UX point of view, but you should also be doing it server-side as well.

If this is a Vue app, write a custom validator for Vee Validate


frontend form action: save as draft or publish

I believe you're looking for entryRevisions/publishDraft:

<input type="hidden" name="action" value="entryRevisions/publishDraft">

You can see the specific inputs it is looking for here: https://github.com/craftcms/cms/tree/master-v2/src/controllers/EntryRevisionsController.php#L188


Loop through fields in field layout when `entry` is not set

This can be done by reaching through the section and entry type to the final field layout. Like this:

{% set section = craft.sections.getSectionByHandle('sectionName') %}
{% set entryType = '' %}
{% for type in section.getEntryTypes %}
    {% if type.handle == 'entryType' %}
        {% set entryType = type %}
    {% endif %}
{% endfor %}
{% set fieldLayout = craft.fields.getLayoutById(entryType.fieldLayoutId) %}

You should be abel to use getFields as normal.


You will need to add a template called test.html that extends the "_layout.html" template. The layout template is just a wrapper template, and with the "_" in front of it, it will always be invisible to a browser.

Take a look at the twig references on extending templates. Also look at the templates supplied with the initial install to get a better idea how this works.

Twig Extend

Routes are for more refined routing of templates and you should not need a route for current implementation.

Imagine if "_layout.html" were named "_wrapper.html" and it makes a little more sense.


You're asking kind of a loaded question but as far as Craft is concerned, you're in a good position to spit out exactly what you need as far as markup and styles go. AMP is more or less just a small subset of HTML.
When compared to something like WordPress, Craft is going to give you all the tools necessary to spit out an AMP page just by virtue of it doesn't dictate layout and styling nor include any extra fluff. And it provides easy routing features to make it easy to make different "versions".
Different Versions / Different Routes
Depending on how your site is setup, you'll want different versions of your content—one regular and one for AMP... not unlike the old m dot sites. (Taking it back to the old school WAP era I guess...)
Let's say you have a section called News.  If your entries URL Format looks like: http://site/news/slug/, you might want to have the AMP version look like http://site/news/slug/amp.
One way to do that in Craft is to setup a route. You can do that in Settings -> Routes -> New Route.

That will load the _amp.html template inside a news folder. You'll have to do a little extra work to tell Craft where to pull the entry from since routes only load templates by default. Since we used the slug variable in our routes, we can use that to grab the entry from the news section and also set the entry variable.
{% extends "_layoutamp" %}

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

{% block content %}
  ... rest of your content
{% endblock %}

The AMP docs start with a simple skeleton. I used {% extends "_layoutamp" %} in our _amp template so we need to make a  ``_layoutamp.html" file to match inside Craft's templates folder.
   {# _layoutamp.html #}
    <!doctype html>
    <html amp lang="en">
      <head>
        <meta charset="utf-8">
        <title>{{entry.title}}</title>
        <link rel="canonical" href="{{entry.url}}" />
        <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
        <script type="application/ld+json">
          {
            "@context": "http://schema.org",
            "@type": "NewsArticle",
            "headline": "{{entry.title}}",
            "datePublished": "{{entry.dateCreated.iso8601()}}",
            "image": [
              "logo.jpg"
            ]
          }
        </script>
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
        <script async src="https://cdn.ampproject.org/v0.js"></script>
      </head>
      <body>
        {% block content %}
           {# brings in the content from the _amp.html content block #}
        {% endblock %}
      </body>
    </html>

AMP recommends some metadata near the top, in the form of JSON. Easy enough to spit out the required fields in Twig.
"Linking" to an AMP page
You'll notice a <link rel="canonical" href="{{entry.url}}"> in that file as well to tell Google your main version is here.
On your "normal" page, you'll want to add a reference to the AMP page too. (I also like to set the canonical version as well for good measure.
<link rel="canonical" href="{{entry.url}}">
<link rel="amphtml" href="{{entry.url}}/amp">

That will tell Google the AMP version is at the URL.
Anything else?
Pretty much the rest is up to you. AMP is pretty easy to setup but you still need to use their custom tags.
Most notably, things like images and videos need to use custom tags like amp-img and amp-video, so the AMP runtime can intercept the loading of those assets and handle them.
Will be interesting to see how this affects page rank moving forward. Google confirmed it's not a ranking signal (yet) but that doesn't mean it won't be in the future.


Try
{% set recentHistory = order.histories|first %} // get the first order history item
{{ recentHistory.dateCreated|date ?? 'no history record' }}

there is no date attribute on an order history model, just the dateCreated. So in effect you are passing null to the |date filter which will default to the current time/date.
You were trying to access the current order status model on the order. There is no dateCreated on the order status model, only the model itself. The date the order status was applied is in the orderHistory models.


How can I reload the Live Preview Iframe window using JS

All you need to do is

Craft.livePreview.updateIframe(true);

to update the Live Preview iFrame


Show only children relative to current page

Don't use the nav tag. Assuming a structure called pages, try something like this:

{% set pages = craft.entries.section('pages').level(1).all() %}

{% for page in pages %}

        {{ page.title }}
        {% if entry is defined and entry.hasDescendants %}
            {% set children = page.getChildren() %}

            {% for child in children %}

{{ child.title }}

            {% endfor %}

        {% endif %}

{% endfor %}


HTML being stripped/replaced by redactor on initialising despite being saved correctly

Have you tried using the allowedTags attribute in your Redactor config?

$('#redactor').redactor({
    allowedTags: ['div','p', 'h1', 'h2', 'pre']
});

You can read about that here:

http://imperavi.com/redactor/docs/settings/clean/#setting-allowedTags


I think you are mixing up your Primary Plugin Class with your Dashboard Widget.

Plugin Structure:

Assuming your plugin is called Gareth and your widget Gr, this files should be in your /craft/plugins/gareth/ directory:

GarethPlugin.php
templates/

GrWidget.html

widgets/

Gareth_GrWidget.php

Primary Plugin Class: GarethPlugin.php

  Your primary plugin class defines all of the things that Craft needs
  to know about your plugin, such as the plugin’s name, version number,
  developer’s name and URL, and Global Settings.

<?php
namespace Craft;

class GarethPlugin extends BasePlugin
{
    function getName()
    {
         return Craft::t('Gareth');
    }

    function getVersion()
    {
        return '1.0';
    }

    function getDeveloper()
    {
        return 'Gareth Redfern';
    }

    function getDeveloperUrl()
    {
        return 'http://garethredfern.com';
    }
}

Widget Class: Gareth_GrWidget.php

This class defines the widget types name getName() and its content getBodyHtml().

<?php
namespace Craft;

class Gareth_GrWidget extends BaseWidget
{
    public function getName()
    {
        return Craft::t('Gr');
    }

    public function getBodyHtml()
    {
        return craft()->templates->render('gareth/GrWidget');
    }
}

Widget Template: GrWidget.html

This is just some text which will be shown inside the GrWidget.
A link to my user profile

Result:

More:

Check out the Widget documentation. Also take a look at Craft's default widgets which can be found in the craft/app/widgets directory.


Use `onBeforeSaveEntry` event to update EntryModel properties?

Just looking through the source file, it looks like sectionId, typeId, authorId, postDate and expiryDate are all set as properties on the $entryRecord before the onBeforeSaveUser event is fired. It also looks like $entryRecord is not accessible from the event, nor is it saved yet such that you could modify it directly. I suspect that you will need to modify these properties after the entry is saved (using the onSaveEntry event), and then resave the entry. You will also of course need to add conditionals (i.e. compare current authorId to target authorId) and only save the entry if needed, to ensure that you don't create an endless loop.


Adding a cite tag within the blockquote tag using redactor's WYSIWYG?

You can use the Redactor Inline Styles add-on then use the following in your Redactor json config:

"plugins": ["source","fullscreen","inlinestyles"],
    "buttonsAddAfter": "italic",
    "buttonsAdd": {
        "cite": {
            "title": "Cite",
            "args": ["cite"]
        }
    }

You'll then be able to add a cite element within a blockquote formatted text.


How can I get the id of an unverified user on front-end?

You can get the user by email

{% set user = craft.users.status(null).email("a@b.de").one() %}
{{ user.id?? 'no user found' }}


What it "Assets in this source have public URLs" good for?

It let's you define "private" asset sources that you don't want publicly exposed on the web.

  Another question: when I upload assets to craft, sometimes they are put in the folder I expect, sometimes craft creates a subfolder (named like the asset-id I guess) and puts the file inside that folder.

If you're uploading these files through an Assets field, then that field's setting can define a dynamic subfolder path where the upload will be saved based on the contents of the entry/user/tag/category/etc. that it is being saved in.  Sounds like that's what you've got defined.


Sortof – you can find out what an image’s width would be with a transform applied to it via AssetFileModel’s - getWidth() and getHeigth()

 970 -%}
        {{ image.getUrl(transform) }}
    {%- else -%}
        {{ image.url }}
    {%- endif %}" alt="{{ image.title }}" />

And for extra cleanliness points, you can update the code to use setTransform() instead of jumbling all that code into your  tag:

{% if image.getWidth(transform) > 970 %}
    {% do image.setTransform(transform) %}
{% endif %}


Without understanding your use case or having the context of your full template and/or Matrix loop, it's very difficult to provide a good answer.

If you only want to "wrap all outputted blocks" in a container, it's as easy as putting the Matrix loop in a container, e.g.:

    {% for block in entry.myMatrixFieldHandle %}
        {% switch block.type %}
            {% case 'artworkText' %}
                ...
            {% case 'artworkImageSingle' %}
                ...
            {% case 'artworkImageDouble' %}
                ...
            {% case 'artworkFile' %}
            {% for asset in block.downloadUrl %}

            {% endfor %}
        {% endswitch %}
    {% endfor %}

Based on your comments, however, I suspect that what you really want is to only wrap the markup for all your artworkFile blocks.

If that is the case, you have to consider the fact that if you want to wrap all of the artworkFile blocks in a single container and not the other block types, then these artworkFile blocks will necessarily be removed from the general flow/chronology of your overall Matrix field. This may be exactly what you want, or a side effect you haven't considered - just wanted to mention it. (It also means that you could actually just move the artworkFile blocks to a separate Matrix field altogether, if that'd make any of this easier).

Anyway, there's at least a couple of ways to achieve the above with your current setup.

First, you can opt to remove the artworkFile switch case from your current Matrix loop, and create a secondary loop which only loops on artworkFile blocks somewhere else in your template. This secondary loop is then wrapped in a
 container, e.g.:

    {% for block in entry.myMatrixFieldHandle.type('artworkFile') %}
        {% for asset in block.downloadUrl %}

        {% endfor %}
    {% endfor %}

Another option is to leave the artworkFile switch in your current Matrix loop, but instead of outputting the markup directly, you can cache it in an array – this is done by first putting the markup in a variable by wrapping the block markup in a {% set %} tag pair, adding that variable to an array declared outside the loop, and finally print the collected markup by joining the contents of that array inside a container, e.g.:

{# Create an empty array outside the loop #}
{% set artworkFileBlocks = [] %}
{% for block in entry.myMatrixFieldHandle %}
    {% switch block.type %}
        {% case 'artworkText' %}
            ...
        {% case 'artworkImageSingle' %}
            ...
        {% case 'artworkImageDouble' %}
            ...
        {% case 'artworkFile' %}
        {# Cache the markup for the artworkFile block to a variable #}
        {% set artworkFileBlock %}
            {% for asset in block.downloadUrl %}

            {% endfor %}
        {% endset %}
        {# Add the single artworkFile block markup to the array #}
        {% set artworkFileBlocks = artworkFileBlocks|merge([artworkFileBlock]) %}
    {% endswitch %}
{% endfor %}

{# Echo all artworkFile markup in a common container, whereever you need it #}

    {{ artworkFileBlocks|join('')|raw }}


My website isn't working: "Craft does not support backtracking to this version. Please upload Craft 2750 or later."

Sounds like your database was updated but your filesystem was not - that could happen perhaps if the development version and the live version share the same database, and only the development version ran the update.

To fix it try renaming the craft/app folder to craft/app-old, then copy the craft/app folder from the latest Craft download into your site.

Backup your stuff first.


Output specific entry from entries field based on position

{% set allEntries = entry.entriesSelector.all() %}

First: {{ allEntries[0].title }}

Second: {{ allEntries[1].title }}

Fourth: {{ allEntries[3].title }}

Last: {{ allEntries|reverse[0].title }}