Ability to SUM() or GROUP BY from the template or ElementCriteriaModel

You could do this with a plugin. Create a Variable class with a function called sum(), which accepts an ElementCriteriaModel, passes it to ElementsService::buildElementsQuery(), and then replaces the SELECT value on the resulting DbCommand object:

<?php
namespace Craft;

class FooVariable
{
    public function sum(ElementCriteriaModel $criteria, $column)
    {
        $query = craft()->elements->buildElementsQuery($criteria);

        if ($query)
        {
            return $query
                ->select("SUM({$column})")
                ->group(null)
                ->queryScalar();
        }
    }
}

With that in place, you can do this in your templates:

{% set entries = craft.entries.section("mySection") %}
{% set sum = craft.foo.sum(entries, "field_myCustomField") %}

Note that you will need to pass in the field’s full column name (with that “field_” prefix) rather than just its handle. You can figure that out by looking at your craft_content table (or craft_matrixcontent_matrixfieldhandle if it’s a Matrix field). It would have been possible to get the code to be smart enough to figure the column name out for itself, but this way is a bit simpler.


How to display an entry on frontend with status disabled if admin is logged in?

If you're specifically checking for the admin, then it's more like:

{% if currentUser.admin %}
    {% set slug = craft.request.lastSegment %}
    {% set entry = craft.entries.slug(slug).status(null).first %}

    {{ entry.title }}
{% endif %}

If you're getting a 404, then it's some other routing issues that is occurring.


Outputting Year of Entry Group alongside Month

You're close!

We've got an example of how to do this here: http://buildwithcraft.com/help/entry-archive#grouping-by-year-and-then-month

The trick is to group by year first, then by month.  Using the 'F' token is how to tell PHP to display the name of the month.


Is there any Booking/Reservation system for Craft 3?

Whilst one could build a booking system within Craft either with judicious use of Twig, Channels, and Entries or with a custom plugin it doesn't make a huge amount of sense to reinvent the wheel. Especially when booking management systems are deceptively complex when you get past the initial idea.

It would be possible to integrate pretty much any third party booking system into Craft with a bit of custom plugin development.


If your categories are only one level deep, you could hard-code the breadcrumbs into the category template:

{% block breadcrumb %}

Blog

{{ category.title }}

{% endblock %}

In _layout.html you would have:

{% block breadcrumb %}

Blog

    {% if craft.request.segments %}
      {% for crumb in entry.getAncestors() %}

{{ crumb.getLink() }}

      {% endfor %}

{{ entry.title() }}

    {% endif %}

{% endblock %}

Haven't tried this myself, but I think it would work - the category template would override the layout.

Of course, if you have multiple levels of categories, the intermediate levels won't be included, so it's not an ideal solution.


DevMode Class 'Exception\RuntimeException' not found

Definitely agree with the comments that you should enable devMode from day one when working on a project. In addition, coding defensively can help avoid common frontend errors as well.

There's more on this topic in the article Handling Errors Gracefully in Craft CMS


Plugin migration - calling services help

I can't answer the question fully without seeing your plugin code, but I'd suggest you generate your plugin scaffolding with pluginfactory.io to see how it all fits together.

It's also helpful to look at a existing plugin that works; here's one I wrote that's pretty simple, and should be easy to follow: FastCGI Cache Bust

Roughly, you'd do something like:

PluginClass::getInstance()->serviceName->methodName();

Or if you do it the pluginfactory.io way:

PluginClass::$plugin->serviceName->methodName();


Draft from front-end form with limited field set

Too bad no one could help me, but found a solution in the meantime. Inspired by others on Github and Stackoverflow (https://craftcms.stackexchange.com/a/14158/3937). Maybe my solution helps someone else with the same problem.

I created a method in my controller which gathers all values from the fields and prepares an array of it, which has exactly the same format as the CP in the browser sends when saving a new draft. I use this array to feed the method setContentFromPost on the EntryDraftModel, together with the incoming POST data from craft()->request->getParam('fields').

public function getFieldValuesFromEntry(BaseElementModel $entry, $fields = null)
{
    foreach ($entry->fieldLayout->fields as $fieldLayoutField) {
        $fieldHandle = $fieldLayoutField->field->handle;
        if ($fields === null || in_array($fieldHandle, $fields)) {

            $fieldValue = $entry->getFieldValue($fieldHandle);

            if ($fieldValue instanceof RichTextData)
            {
                $value = $fieldValue->getRawContent();
            }
            elseif ($fieldValue instanceof ElementCriteriaModel)
            {
                $value = $fieldValue->ids();
            }
            elseif ($fieldValue instanceof SingleOptionFieldData)
            {
                $value = $fieldValue->value;
            }
            else
            {
                $value = $fieldValue;
            }

            $field[$fieldHandle] = $value;
        }
    }

    return $field;
}

And this is the snippet where I feed it into the draft ($entryFields is here the output of the method above):

$draftFields = craft()->request->getParam('fields');
$draft->setContentFromPost(array_merge($entryFields, $draftFields));

If anybody has a more efficient solution to fix my problem, please let me now. Cheers!


Is there a way to see a fields variant relation in templates?

yes, you could filter the variants for the status enabled to output only the enabled variants of the product.

 {% set products = craft.products.all() %}
 {% for product in products %}
     {{ product.title }}

     {% set variants = product.variants|filterByValue('enabled', "1") %}
     {%- for purchasable in variants -%}
          {{ purchasable.id }} - {{ purchasable.description }} - {{ purchasable.price }}

     {%- endfor -%}
 {% endfor %}


Twig variables wont work in an include js file?

There is no "syntax" for it since you don't parse these files with PHP.
You'll have to declare your variables inside a twig file

First Approach

Twig

Javascript

jQuery(document).ready(function(){
    var uspicon1 = myVariable.usp_1_icon;
    var uspicon2 = myVariable.usp_2_icon;
    var uspicon3 = myVariable.usp_3_icon;
    var uspicon4 = myVariable.usp_4_icon;
    jQuery('.icon1').addClass(uspicon1);
    jQuery('.icon2').addClass(uspicon2);
    jQuery('.icon3').addClass(uspicon3);
    jQuery('.icon4').addClass(uspicon4);
});

Second Approach

Or you move your Javascript inside a Twig file

{% js %}
jQuery(document).ready(function(){
    var uspicon1 = "{{ theme.usp_1_icon }}";
    var uspicon2 = "{{ theme.usp_2_icon }}";
    var uspicon3 = "{{ theme.usp_3_icon }}";
    var uspicon4 = "{{ theme.usp_4_icon }}";
    jQuery('.icon1').addClass(uspicon1);
    jQuery('.icon2').addClass(uspicon2);
    jQuery('.icon3').addClass(uspicon3);
    jQuery('.icon4').addClass(uspicon4);
});
{% endjs %}

You can as well attach the attributes in your html - that makes it much easier

Third Approach

Twig

Javascript

var element = jQuery('.icon4')
element.addClass(element.data('class'));


Updating the Database for plugin settings

You don't need to create Records, Models or interact with the database to store your plugin settings – Craft handles this for you out of the box. Here's how:

In your main plugin file (PluginNamePlugin.php):

protected function defineSettings()
{
    return array(
        'radioGroupName' => array(AttributeType::String, 'default' => 'option_1')
    );
}

public function getSettingsHtml()
{
   return craft()->templates->render('pluginname/settings', array(
       'settings' => $this->getSettings()
   ));
}

At a glance, your settings template looks fine, and should be placed within the pluginname/templates/ directory (filename settings.html).

If you want to retrieve a setting somewhere else within your plugin's main class, you can do it like this:

$settings = $this->getSettings();
$radioGroupName = $settings->radioGroupName;

To read the settings outside the main plugin class, you'll first need to pull the plugin instance, like this:

$plugin = craft()->plugins->getPlugin('pluginName');
$settings = $plugin->getSettings();
...

If you want to retrieve your setting(s) for use in templates, you'll need to create a template Variable class for your plugin in order to expose the data. Here's a quick example for your use case (the following would go into the file pluginname/variables/PluginNameVariable.php:

class PluginNameVariable
{
    public function settings()
    {
        $plugin = craft()->plugins->getPlugin('pluginName');
        return $plugin->getSettings();
    }
}

...and in your template:

{% set settings = craft.pluginName.settings %}
{{ settings.radioGroupName }}

For more info on plugin settings, see the official docs on the subject: http://buildwithcraft.com/docs/plugins/plugin-settings


Output Placeholder, Max Length, Line Breaks, Initial Rows values for Fields in Sprout Forms

The problem is due you're trying to get a property from the FieldLayoutModel instead of FieldLayoutFieldModel please see the code bellow to fix the error.

{%- set layoutFields = tab.getFields() %}

    {% for layoutField in layoutFields -%}

        {%- set field     = layoutField.getField() -%}
        {{ field.settings.placeholder }}
    {% endfor %}


How can I keep the Compiled Templates from caching during development?

If you're in devMode, then Twig's compiled templates will be regenerated on every request.  Otherwise, they'll be regenerated when Twig sees that the source template's date modified timestamp has changed.

As of PHP 5.5+, PHP's opCache is enabled by default, which might explain what you're seeing. If you're in development, you'll want to disable that to make sure PHP isn't doing any caching at the byte level.


Is it safe to mass delete users from the database directly

If you want to delete users (or any other elements in Craft) directly from the database, the place to do that is the elements table. Delete the row(s) from there, and all the elements’ rows in the other tables will go away automatically.


Creating JS slideshow with Twig "for" loop

You didn't mention you want to style your sliders differently. I don't think you have to address them separately form your JS and CSS, if they should all look just the same.

HTML:

{% for slider in entry.myMatrixField.type('slider') %}
    <div class="royalSlider">
    </div>
{% endfor %}

JS:

$('.royalSlider').royalSlider({
  controlNavigation: 'bullets'
});

CSS:

.royalSlider {
  width: 300px;
  height: 200px;
  background: red;
}


Can I create multiple website using the same admin control panel and what I have to change for that?

Yes, you can create it. Follow below steps and create new website using same control panel.
You should go to Settings > Sites
You can create another website using same admin
Handle site at section level as per your requirement
Make required changes as mentioned below.

.env file in create environ variable.

Same variable use in config>generale.php file same as “dev”.

Admin side setting>site>change primary side which site you want to execute at front end

You don't need the Craft Pro for this feature. You can do that with Craft Solo as well.


This is basically just a syntax error. What you are doing is: searching for entries in the group section: 'markets', with: ['bannerImage'] but what you want is searching for categories in the group markets with the field bannerImage

{% set markets = craft.categories.group('markets').with(['bannerImage']).all() %}

The group parameter in your CategoryQuery defined which group(s) you want to select. The with parameter your eager-loading elements. Btw: Categories have no section property


Avoiding initial load for image transform

You can tell Craft to generate new image transforms right when getUrl() is called by setting the generateTransformsBeforePageLoad config setting to true. Assuming you still want the default behavior on your main website, you can set the setting programatically from your endpoint config with ConfigService::set():

'endpoint/path' => function() {
    craft()->config->set('generateTransformsBeforePageLoad', true);

    return [
        // ...
    ];
},


Depending on how your plugin is setup, you should likely be setting model attributes in your Services. Create a new Model object, set its attributes, then pass that Model to the proper Record and save it.

Of course, this all varies based on what you're doing with it. If you provide more information, I'll see if I can lend a hand.


Unexpected token "name" of value "name" ("end of statement block" expected)

This line is incomplete:

{% set order = craft.commerce


In your plugin have you tried updating the currency and paymentCurrency fields in the craft_commerce_orders database table?

Depending on when you want to set the currency and how you are determining it, you could either do this by a direct database query, or modify the values in the order model before it is saved using this hook: https://craftcommerce.com/docs/events-reference#commerce_orders.onbeforesaveorder


From a Twig template, how to retrieve the content of a HTTP header in the current request?

By checking the code, I could find a method named getHeaders() that will return all the headers of the current request.

So if you want to retrieve the content of the foo header, just use:

{% set headers = craft.app.request.getHeaders() %}
{% set fooHeader = headers['foo'] %}


There is a second parameter  in your setAttributes() function. This parameter is true per default and checks if the attribute is safe so you either have to declare all safe attributes in your records rules or you set the parameter to false.


I base my example on the assumption that all people are Users (Element type User). If users are entries, you'd have to replace users by entries ;)

I don't think there's a way to do this without iterating through all users first, creating some sort of ordering attribute (if lastName != '' ? lastName : firstName). Then, you'd be able to group your array by your ordering attribute:

{# create a variable to hold all user data you need #}
{% set allUsers = [] %}

{# loop through users ... #}
{% for user in craft.users.find() %}
    {#
        ... and set variable for each user, containing the info you need
        and an 'orderMeBy' attribute, set to the uppercased first character of lastName or firstName
    #}
    {% set thisUser = [{
        fullName : user.fullName,
        orderMeBy : user.lastName != '' ? user.lastName | slice(0,1) | upper : user.firstName | slice(0,1) | upper
    }] %}

    {# merge this user's info with your allUsers variable #}
    {% set allUsers = allUsers | merge (thisUser) %}
{% endfor %}

{# group 'allUsers' variable by 'orderMeBy' attribute #}
{% set groupedUsers = allUsers | group('orderMeBy') %}

{# create an array of all numbers and letters #}
{% set numbers = 0..9 %}
{% set letters = 'A'..'Z' %}
{% set allChars = numbers | merge(letters) %}

{# loop to chars and, if users in groupedUsers[char], display those users #}
{% for char in allChars %}
    {% if groupedUsers[char] is defined %}

{{ char }}

        {% for user in groupedUsers[char] %}

{{ user.fullName }}

        {% endfor %}

    {% endif %}
{% endfor %}

If anyone knows a quicker and/or easier way, tell me :)


Hide navigation from one entry but not others

This line:

{% set hideMenu = craft.entries.section('mysection').showMainNavigation('not 1').one() %}

will return the first entry that it can find in the section 'mysection' that has showMainNavigation off. So as soon as you disable it for one entry, hideMenu will 'return' true, whichever page you're on.

So to fix this, if mainEntry is your current entry, then replace the line by:

{% set hideMenu = mainEntry.showMainNavigation %}


Something like this should work:

{% set userGroups = craft.userGroups.getAllGroups() %}

{% if userGroups|length %}
    {% for userGroup in userGroups %}

            {{ userGroup.name }}

        {% set users = craft.users.group(userGroup.handle) %}

        {% for user in users %}

                {{ user.username }}

        {% endfor %}

    {% endfor %}
{% endif %}


Adjust item stock accordingly to checkout carts

Well I made a workaround, I'm going to use Custom Order Status to manage "in stock" and "pending in cart" and get both the values and make a calculation that will be put in the "stock" value displaying in the front.


The reason there is a "Purify HTML?" setting only for Rich Text fields is that Twig will automatically escape the output of every other field by default, mitigating XSS attack vectors.

Rich Text fields, by nature, are designed to store HTML, therefore their output isn't escaped and you have to rely on things like "Purify HTML?" (which uses http://htmlpurifier.org/) to try and remove anything malicious looking.

If you're plugin needs to output data for a Plain Text field in a way that doesn't get escaped (for whatever reason), you can always run HTMLPurifier on it manually.


Multi-Language Site but the Date should be always in English

I made a plugin to do this.

https://github.com/IndigoViking/Translitedated

Use it just like the |date filter (new filter is |dated) and pass it the date format and the locale you would like to use. In you case the locale would be 'en'.

Example from your question:

{{ block.timeLimit|dated('M d Y H:i', 'en') }}

This will always output an English date.

If you have any issues with it, just submit an issue via GitHub.

It's available via packagist so you can run

composer require indigoviking/translitedated

And it is in process to be approved on the plugin store (should only be a day or so. If you need more features/requests/or help with it, please let me know!


Yearly/Monthy archive listing sorted by month

Add the reverse filter to your inner array of entries in month.
http://twig.sensiolabs.org/doc/filters/reverse.html


Can Craft be run on NearlyFreeSpeech.NET?

Yes, it is possible to run Craft CMS NearlyFreeSpeech.NET. I did it as follows:

Place the Craft folder in /home/tmp.
Place the files in the public folder in /home/public.
Change the permissions of the craft folder and all subfolders and all files to 777.
Change craftPath in index.php to '../tmp/craft'.

Perhaps it would not be necessary to change all subdirectories and files in the craft folder to 777. But it is the easier way and it should hopefully not create a problem, because the folder is not accessible from the public. Even the update process is running if the folder (including subfolders and files) is 777.


Well done for working out how to display "reverse-related" entries!

In order to separate your Articles into two lists i.e.

Articles with downloads
Articles without downloads

... I would do something like the following on your Company single-entry template...

{% set relatedArticles = craft.entries.section('article').relatedTo() %}

{# Related articles which have downloads #}
{% for articleEntry in relatedArticles %}

    {# check for Matrix content #}
    {% if articleEntry.downloads != '' %}

{{ articleEntry.title }}

            {# loop through any matrix items #}
            {% for block in articleEntry.downloads %}

                {# get the first asset into a variable named 'download' #}
                {% set download = block.downloadFile.first() %}

{{ block.downloadName }}

            {% endfor %}

    {% endif %}
{% endfor %}

{# Articles which do not have downloads #}
{% for articleEntry in allArticles %}

    {# check for blank Matrix content #}
    {% if articleEntry.downloads == '' %}

        {# display article titles #}

{{ articleEntry.title }}

    {% endif %}
{% endfor %}

Hope that helps. Let us know how you get on...


How to add custom user fields to the front end registration page

You need to change your input tag from:

<input id="Address" type="text" name="Address"
{%- if account is defined %} value="{{ account.Address}}"{% endif -%}>

To:

<input id="Address" type="text" name="fields[Address]"
{%- if account is defined %} value="{{ account.Address}}"{% endif -%}>

All custom fields input types should have a name prefixed with fields[].


Clearing temporary assets from craft/storage/runtime

In Craft 2 the only real solution is to delete all the entries from craft_assetfiles where the sourceId is set to null.

The reason why there's no clear cache tool for these is because that might allow for deletion of Assets that were just uploaded by someone else who might be about to use them.

This is really far from a practical solution and we know that, but it's not easily improved in Craft 2.

Craft 3 will slightly improve things by adding a "Temporary uploads" Asset volume which will hold all of the current user's leftover Assets, allowing you to deal with them as you would with regular Assets.


Use value of a dropdown field for an `include`

You don't need to (more specifically, you can't) nest Twig tags within other Twig tags. Ditch the inner Twig tag and its respective quotes, and just pass the variable directly into the outer Twig tag...

{% include entry.dropSubsection %}

That being said, I'm not sure this will achieve exactly what you're looking for. You may need to append .value as well...

{% include entry.dropSubsection.value %}


Craft CMS: Data too long for column 'cacheKey' at row 1

Is there a Craft recommended approach to this issue please?

The simplest solution would be to update to Craft 3.5+
Template cache data went from being stored in the database to the file system, so this won't be an issue for you anymore.


Craft 3 : What are the advantages to use PostgreSQL and when should I use it instead of MySQL?

This isn't actual first-hand experience talking, but from what I've read, Postgres will start to see gains when we're talking about very large data sets, either in terms of the size of the columns, or the number of rows in a particular table.

As mentioned in the quote above, Postgres also has some other nicities as well. The downside is that there is less tooling around Postgres than there is MySQL, so while you'll be able to find GUI clients, they aren't there in quantity or quality compared to MySQL.

I have had devMode.fm up and running with Craft 3 and Postgres since day 1, in part to get Craft-Scripts working with it (which it does) since it's a supported database type by Craft now, and then also in part just to kick the tires.

What I can tell you is that everything "just works" from a Craft POV. I haven't had any issues at all with the Craft APIs, and since I do the database syncing with Craft-Scripts, the tooling hasn't matter either (but the editor I user is PhpStorm, which can connect to Postgres databases anyway).

You will most likely have to learn a bit about about Postgres handles access permissions, because it's quite different from MySQL, but that's not so bad really.

After using it for a while, my conclusion is that it works fine; but on a small site like devMode.fm, it probably makes absolutely no difference. Because it doesn't have any large db columns or massive numbers of rows of the like. You'd never notice the difference from a frontend/AdminCP POV in terms of which db driver you're using, which is a testament to the work that P&T and the Yiisoft folks have done.


Error when trying to update Craft or install any plugin

"repositories": [
    {
      "type": "path",
      "url": "plugins/redactor"
    }
  ]

With that in your composer.json file, you're telling Composer to look in a plugins/redactor folder from the root of your project and use that to satisfy the "craftcms/redactor" dependency (instead of pulling it from packagist.org).
https://getcomposer.org/doc/05-repositories.md#path
That error is saying that the plugins/redactor folder doesn't exist. The most common use-case for that is you've got a separate fork of the plugin you're using, but if that's not the case, you can remove that whole repositories section and it'll start using the official redactor release from packagist.


Login Page Logo and Site Icon with Project Config

System Settings don't support rebranding via Project Sync, however if you place your assets in the following locations and commit to GIT you can get similar results.

Login Page Logo -> <project_root>/storage/rebrand/logo/<filename>.svg
Site Icon -> <project_root>/storage/rebrand/icon/<filename>.svg

By placing the images in the above locations the system will automatically detect them. You should then see them show up in the backend without needing to upload them also.


Do 404s get access to variables set with setRouteVariables?

The simple answer is: no, error handling templates don’t have access to the variables that would be available to the template when the request resolves normally. And we won’t be making it possible.

Technically you could get access to them by creating a plugin that has a template hook which is capable of adding those variables:

craft()->templates->hook('mergeRouteVariables', function(&$context)
{
    $routeParams = craft()->urlManager->getRouteParams();

    if (isset($routeParams['variables']))
    {
        $context = array_merge($context, $routeParams['variables']);
    }
}

404.html:

{% hook "mergeRouteVariables" %}
{# ... #}

  It's probably worth noting that the reason I'm trying to do this is because I want to include a form on the 404 page (that I also include in other areas, so it's setup as a partial) and I'm having trouble passing error validation back and forth with setRouteVariables, but only for 404 pages. I know I could do this with a session and that is my current work around, but I wanted to see if there was a better way.

While I understand your use case, it's pretty weird that you would have a form that intentionally submits to a 404 page (even though it’s the same page).

Here are a couple alternatives you might want to consider:

You could create a dedicated page for the form, and have the form submit to that page’s URL in the event that it’s coming from a 404.
You could handle the form submission and validation with Javascript/Ajax.


Matrix | Craft 3 Element API / Scout Plugin

The first code section looks correct, other than that you're first creating a bodyBlocks array and then assigning a string to it, but that's not really consequential and not the issue behind this failing.

Do yourself a favor and set up PHPStorm + xdebug, you'll find the issue very easily. I suspect you might have some mixed up identifiers (field names, block handles) etc.


https://straightupcraft.com/craft-plugins/?q=analytics& shows some possible analytics candidates.

Particularly these:

https://straightupcraft.com/craft-plugins/instant-analytics

https://straightupcraft.com/craft-plugins/piwik-analytics

https://straightupcraft.com/craft-plugins/3redkites-piwik-analytics-for-craft-cms

https://straightupcraft.com/craft-plugins/tracker


How to get the unique categories from a list

Maybe not the most elegant, but something like this should work:

{% set entries = craft.entries.section('faqs') %}
{% set usedCategoryIds = [] %}

{% for entry in entries %}
    {% for category in entry.faqCategory %}
        {% if category.id not in usedCategoryIds %}

{{ category.title }}&nbsp;

            {% set usedCategoryIds = usedCategoryIds|merge([category.id]) %}
        {% endif %}
    {% endfor %}
{% endfor %}


Smart Map Lat+Lng is present but no pin on map

As Craft defaults to only returning 100 elements, setting the limit(null) parameter to the query fixed this issue.

{% set locations = craft.users.group('fullMembership').limit(null) %}


The logo you upload there will replace the default Craft graphic on the login page for the Control Panel.


Multisite Craft 3, different entries on different sites

For future reference, this was fixed in 3.0.0-RC15

  Added the “Propagate entries across all enabled sites?” section setting. If disabled, entries will only be associated with the site they were created on.


Short answer; no. Craft uses a database to store and query for content and doesn't have any way to work with content in files the way that Statamic has.

But, migrating the content into Craft's database doesn't have to be a big challenge.

If you're a PHP-developer, creating a plugin that parses the files and inserts the content into Craft is a breeze.

If you're not a developer (or if you are, but prefer a less code intensive way of doing it), there're several plugins for Craft that helps you importing content into the Craft database. Have a look at Feed Me from engram design, or Import from Bob Olde Hampsink. You'd then create a simple front-end template in Statamic that queries the data you want to move over, outputs xml or json, and then send that data to the plugin which do the heavy lifting.

I've used Feed Me on several occasions to move data from ExpressionEngine sites to Craft, and it works great.


How to deal with client input your site?

Not an answer, but one thing that might help you diagnose the problem, is to output all the return errors (without having to define it on each field as the example templates do).

{% macro errorList(errors) %}
    {% if errors %}

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

{% from _self import errorList %}

{% if account is defined %}
    {{ errorList(account.getAllErrors()) }}
{% endif %}

{% if entry is defined %}
    {{ errorList(entry.getAllErrors()) }}
{% endif %}

A User Model named 'account' is returned by default from a failed users/saveUser post action, and an Entry Model named 'entry' is returned by default from a failed entries/saveEntry post action.

I have also found the Inpector plug-in extremely helpful. You can then add {{ account | inspect }} or {{ entry | inspect }} within the if statements above to get more info.


Update field setting value using getFieldByHandle

MY SOLUTION

Use setAttributes and set the second argument $safeOnly to false

$fieldsService = Craft::$app->getFields();
$field = $fieldsService->getFieldByHandle('productImages');
// Update 'limit' value to be empty in order to accept as many images as needed
$field->setAttributes([
    'limit' => ''
],false);
$fieldsService->saveField($field);


I don't believe there's a more "magic" way than just hard coding the first list item/link, i.e. something like this:

{% if entry.level > 1 %}

            {{ entry.section.name }}

        {% for crumb in entry.getAncestors() %}

{{ crumb.getLink() }}

        {% endfor %}

{% endif %}


You can't use the users.onBeforeSaveUser event to set a user's password as this event happens after the supplied password has been hashed by a private method in the UsersService.

Instead, you could use the users.onSaveUser event, check if a new user has just been saved and if so add the password to the userModel and re-save it. The following is untested, but should do the trick:

    craft()->on('users.saveUser', function(Event $event) {

        // Only fire if new user, this should avoid an infinite loop
        if ($event->params['isNewUser']) {

            // retrieve the userModel from the event
            $user = $event->params['user'];

            // set new password
            $user->newPassword = 'My Super Secret Password';

            // save user
            if (craft()->users->saveUser($user))
            {
                // Password successfully saved!
            }
            else
            {
                // Oops, something went wrong!
            }
        }
    });


Get every slug from entry for each language

Got it...

{% set crawledEntries = craft.entries({
    relatedTo: { sourceElement: crawlSites, field: "entryCrawler" },
    order: "sortOrder"
}) %}

{% set otherLocales = craft.i18n.getSiteLocaleIds()|without(craft.locale) %}

{% for entry in crawledEntries %}
    Disallow: /{{ entry.uri }}
    {% for locale in otherLocales %}
        {% set entryL = craft.entries.id(entry.id).locale(locale).first() %}

        {% if entryL %}
            Disallow: /{{locale}}/{{ entryL.uri }}
        {% endif %}
    {% endfor %}
{% endfor %}


To fix the "No Input File" in your Nginx config, you'll need something like this inside if your php location handler:

    try_files $uri $uri/ /index.php?$query_string;

That will cause it to run the query through Craft (via index.php) if the .php file doesn't exist, which then allows Retour to handle it.

You can see this works by hitting a random .php url on my site: https://nystudio107.com/woof.php

c.f.: https://github.com/nystudio107/nginx-craft/blob/master/sites-available/somedomain.com.conf#L106 & Nginx-Craft


Based on your code excerpts, things look good.  I've encountered issues with spelling and caps  when referencing controllers and templates within my controllers...so pay close attention to them.

I would suggest referencing the 'Cocktail Recipes' sample plugin: https://github.com/seandelaney/cocktailrecipes (Craft 2.x) as it contains an example of what you're trying to do.

EDIT: Updated link to Craft 2.x version as per comment below.


Get a related entries author in a plugin

Something like this should do it:

// Grab an entry.
$entry = craft()->entries->getEntryById(4);

// The current entry's author.
$originalAuthor = $entry->getAuthor();

// This is assuming your Entries field is called "relatedEntry"
$relatedEntry = $entry->relatedEntry->first();

// Make sure one was selected.
if ($relatedEntry)
{
    // The related entry's author.
    $relatedEntryAuthor = $relatedEntry->getAuthor();
}


Unable to edit single or structures, channels working fine after update to Craft 3

Was an issue with my Simple.json redactor config

Was

{
    buttons: [bold, italic],
    toolbarFixed: true
}

Needed to be

{
    "buttons": ["bold", "italic"],
    "toolbarFixed": true
}


I figured it out!

If anyone is stuck at the same place here’s my solution:

{# category is 'ford' #}
{% set entries = craft.entries.section('support').relatedTo(category).find() %}
{% set partsCategories = craft.categories.group('partsGroup').relatedTo(entries) %}

{# Partslist #}
{% for partsCategory in partsCategories %}

    {{partsCategory.title}}
    {% for part in craft.entries.relatedTo([
      'and',
      { targetElement: partsCategory },
      { targetElement: category }
    ]) %}

      {{part.title}}

    {% endfor %}
{% endfor %}


Use a Multi-Environment configuration to set the siteUrl for your two locales, en_au and en_us, independently for each domain like so:

'project.com.au' => array(
    'siteUrl' => array(
        'en_au' => 'http://project.com.au/',
        'en_us' => 'http://project.co/',
    ),
),

'project.co.nz' => array(
    'siteUrl' => array(
        'en_au' => 'http://project.co.nz/',
        'en_us' => 'http://project.co/',
    ),
),

'project.co.za' => array(
    'siteUrl' => array(
        'en_au' => 'http://project.co.za/',
        'en_us' => 'http://project.co/',
    ),
),

'project.co' => array(
    'siteUrl' => array(
        'en_au' => 'http://project.com.au/',
        'en_us' => 'http://project.co/',
    ),
),

You can also set additional environment / domain specific variables in the config file. You could set the currency or the timezone for each domain:

'project.com.au' => array(
    'currency' => 'AUD',
    'timeZone' => 'UTC+10',
    'siteUrl' => array(
        'en_au' => 'http://project.com.au/',
        'en_us' => 'http://project.co/',
    ),
),

This is how you access such a variable in your templates:

{{ craft.config.currency }}


Had a response from Pixel & Tonic on this. Which explains the process.

The problem you're seeing is caused by returnJson() as that also ends the process after outputting the JSON data. Most likely onSaveUser (without Before) is a better place for this code; that ensures the user has been saved to the database before running the event code.


Columns on the Entry index page giving errors

So turns out it was an issue with an older plugin, DashCols. As soon as I disabled it things worked fine.

Unsurprising in hindsight!


Two issues here.

The first error was already a known issue:

General error: 1366 Incorrect integer value

When MySQL's strict mode is enabled, you can get errors like this when swapping an existing field from one type to another where the underlying MySQL datatypes aren't compatible. Swapping from Checkbox to Lightswitch is another time when this could occur.

That one is on our bug tracker, but it's going to be quite an involved fix, so we haven't gotten around to it yet.

The second issue is the one you found. Making the swap from one field type to another and changing the field handle at the same time would not only cause the known error to occur, it would render the rest of the control panel unusable.  That bug has been fixed for the next (post 2.4.2700) release.


How to delete Matrix fields in front end

I've managed to do this with:

<form method="post" accept-charset="UTF-8">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="users/save-user">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">
    {% include '_partial/wish-list-fields' %}

    <input type="hidden" name="fields[userWishListMatrix][{{ block.id }}][type]" value="null">

    <input type="submit" value="Remove">
</form>

The wish-list-fields partial include hidden inputs showing all the fields already there. e.g.:

<input type="hidden" name="fields[userWishListMatrix][{{ block.id }}][fields][itemProperties][0][col1]" value="{{ row.property }}">

It repeats itself which I know doesn't seem terribly efficient but i dunno :-/ It works!

Please note, I'm on craft3 so things may be a little different (although most likely just the save-user / saveUser action).


Basics of overriding an admin page template - Craft 3

There are multiple ways to achieve your goal, I think the most elegant one is to overwrite the default route /users with your custom one and replace the elementType

Things you need to do

Change the default route to your template
Copy the default template and change it's element type
Create a custom element type that extends craft/elements/User

You can change the route of all navigation  bar items (modifyCpNav)

Event::on(
    Cp::class,
    Cp::EVENT_REGISTER_CP_NAV_ITEMS,
    function(RegisterCpNavItemsEvent $event){
        // the 4th element is the "User", you can change the URL to your
        // custom template instead of the default template
        // I suggest you to loop all `navItems` and find
        // the correct user instead of assuming it's the 4th
        // Craft::dd($event->navItems);
        $event->navItems[4]['url'] = 'path/to/template/user';
});

Then just copy the Craft templates/user/index template in your plugin to create an index page

{% if CraftEdition != CraftPro %}
    {% exit 404 %}
{% endif %}

{% requirePermission 'editUsers' %}

{% extends "_layouts/elementindex" %}
{% set title = "Users"|t('app') %}
// changes start
// replace the elementType with your custom element type
{% set elementType = 'prefix\\namespace\\elements\\User' %}
// changes end
{% block actionButton %}
    {% if currentUser.can('registerUsers') %}
        {{ "New user"|t('app') }}
    {% endif %}
{% endblock %}

Then in your src/elements folder create a new User class to overwrite the sources

class User extends \craft\elements\User{ //<-- extend the default User element

    /**
     * @inheritdoc
     */
    protected static function defineSources(string $context = null): array
    {
        $sources = [
            [
                'key' => '*',
                'label' => Craft::t('app', 'All users'),
                'criteria' => ['status' => null],
                'hasThumbs' => true
            ]
        ];

        // Overwrite the sources / usergroups...
        // usually Craft will search for usergroups at this place..
        // just leave it empty, so you'll only see the "default" group

        return $sources;
    }
}

Don't forget to register your element

TL/DR
You could as well just hide the other sources via CSS/Javascript - but I would not suggest it, since everyone is able to see the other groups with minor Javascript skills


DRYer way to set column widths than with if statement?

One way to make it a bit more DRY and flexible is to use the split filter to create an array of column widths.

Also, you can save a bit of markup by calculating the total number of columns, and using a for loop to output the actual column DOM nodes:

{% set columns = content.columnWidth|default('1-2')|split('-') %}
{% set totalColumns = columns[0] + columns[1] %}

    {% for column in columns %}

           [...]

    {% endfor %}


Supersort - Sort multiple variables together

Managed to do this by putting it all into an array:

{% set productID = [] %}
{% set orders = craft.orders().limit(null).all() %}

{% for order in orders %}
    {% for item in order.lineItems %}
        {% set productID = productID |merge([ {
            'productId' : item.purchasable.product.customProductId,
            'groupName' : order.groupName
        }]) %}
    {% endfor %}
{% endfor %}

{% set productID = productID | supersort('sortAs', '{{ object.productId }} {{ object.groupName }}') %}

{% for theID in productID %}
    {{ theID.groupName }} - {{ theID.productId }}
{% endfor %}


Root domain config overriding subdomain config

Craft looks for partial matches to apply config settings (both general.php and db.php which means you can do things like:

'.dev' => array(
..

'.com' => array(
..

Craft applies these settings for each match from the top of the file to the bottom. So in your case because you have the the production domain after your subdomain config it matches and overrides your subdomain settings.

Simply swap your config variables over and it'll work.

return array(
  '*' => array(
    'omitScriptNameInUrls' => true,
    'generateTransformsBeforePageLoad' => true,
    'loginPath' => 'admin',
  ),
  'localhost' => array(
    'server' => 'localhost',
    'devMode' => true,
    'environmentVariables' => array(
      'basePath' => 'C:\wamp\www\craftcms',
      'baseUrl'  => 'localhost/craftcms/',
    )
  ),
  'safs.msu.edu' => array(
    'server' => '35.8.12.67',
    'devMode' => false,
    'environmentVariables' => array(
      'basePath' => '',
      'baseUrl'  => 'http://safs.msu.edu',
    ),
  ),
  'staging.safs.msu.edu' => array(
    'server' => '35.8.12.67',
    'devMode' => true,
    'environmentVariables' => array(
      'basePath' => 'staging',
      'baseUrl'  => 'http://staging.safs.msu.edu',
    ),
  ),
);


Sprout Forms: creating additional text inputs in radio and checkbox labels

The best approach for Radio Button and Checkbox Fields with a Select Other option would be to create a custom field (or fields) using Sprout Forms Front-end Field API.

You could use the existing Radio Button and Checkbox Fields as a starting point and adapt their UI's to present your users with the Select Other option.

You can review the front-end field classes in the Sprout Forms plugin here:

sproutforms/integrations/sproutforms/fields/SproutFormsCheckboxesField.php
sproutforms/integrations/sproutforms/fields/SproutFormsRadioButtonsField.php

It's on our list to add support for front-end fields with this behavior, but it will likely happen after Craft 3 is released. Please reach out if we can help with answering any questions regarding how to implement custom Front-end Fields or custom development support.


Trying to set a dynamic twig variable using craft.request and a craft global

Are you trying to look up the global variable {{ news.pageTitle }} by having the news part be dynamically set from the first segment?

This answer here might help explain. Then try this...

{% set pageTitle = _context[craft.request.getSegment(1)].pageTitle|default("News") %}

I don't think that's the best way to set the displayed page title for your sections, but I believe that's what you're trying to do.

A slightly nicer way would be to also create a page for each section/channel root and have its URL be the same as the base path you use for the entries in those sections. Then you could dynamically look up the page attached to any entry by using this (sorry it's complicated)...

{% set page = craft.enties.url(entry.section.urlFormat|split("{")[0]) %}

That should find the page with the URL that matches the URL of the section entries (up until the first dynamic part). Then you can use the page title, banner, or any other fields you've put on the page.


Sprout Email: "Unable to save recipient."

This was a bug and has been fixed in Sprout Email v2.0.2.


For a Matrix field inside a matrix field I recommend using Supertables.

https://github.com/engram-design/SuperTable

It doesn't look exactly the same as a matrix block but works the exact same way. With supertables you can go as deep as you want.
Super table is a field you can add into your matrix block which is able to use all the fields you want so you dont have any limitations.

My first impression on your Matrix field looks alright to me but, I might misunderstand it.


I am unable to successfully submit guest entries

As per the documentation, you need to include a hidden sectionId field. This specifies the section to which the entry will be submitted.


Here is the Solution. Clearing a couple of lines from the SQL file made it work.


Craft 3: how to show the Yii Debug Toolbar?

There are two checkboxes in your user settings, go to your admin account -> preferences index.php?p=admin/myaccount and check the boxes

This is covered in detail in the Profiling your Website with Craft CMS 3’s Debug Toolbar article


MySQL Collation: utf8mb4_unicode_ci (emojis)

When you create a database in MySQL in Craft 2, you can set the default charset and collation, so that any SQL statements that get executed that don't explicitly specify what charset/collation to use, MySQL will fall back on those.

Craft 2 will always explicitly set what to use based on what the charset and collation database config settings are set to in (by default utf8 and utf8_unicode_ci).  Craft 3 does away with this and falls back on the database default.

However, if you set those config settings to utf8mb4 and utf8mb4_unicode_ci and try to install Craft 2 you'll run into errors:

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes.

Because MySQL's utf8 implementation uses 3 bytes per character and utf8mb4 uses 4-bytes, that pushes many of Craft's indexes over InnoDB's 767 byte limitation.

It's worth noting that if the only place you think you'll need 4-byte support for emojis is in a Rich Text field, then Craft will automatically HTML encode them so they fit in MySQL's 3-byte utf8 charset.

If you need them outside the context of a Rich Text field, then your best bet would be to manually set just that column's charset and encoding to use mb4 in the database directly.

It's also worth noting that the upcoming Craft 3 supports PostgreSQL where none of this matters and it just works.


Element API, query entries where relationship field ':empty:' AND the same relationship field with specified entry ID

Craft will include this functionality in their next release.
https://github.com/craftcms/cms/issues/7256#issuecomment-744644568


No, Craft doesn't have a REST API (edit: or any other web service) built-in. The "API" mentioned in the first quote (and elsewhere related) would be the more generic meaning of the term and refers to the service layer.

With a very consistent MVC based architecture based on Yii, Craft is well suited for REST implementation, though. See this G+ thread for P&T weighing in on the subject.

As a native REST API isn't part of the core, one would have to added to Craft via a plugin.

There's at least one plugin out there, though I haven't tried it (or any others) myself.

Edit

It should be mentioned that after I wrote the above answer, Pixel and Tonic has released the Element API plugin - making it easy to build a REST API with Craft. Element API is pretty basic (only GET requests), but can probably be extended with a custom plugin to support additional HTTP methods.

P&T has also stated that they want Craft 3 to have a full, built-in REST API at some point.


Showing Entries based on an Entries Field but also showing a slug in the url

Set up a custom route in config/routes.php so that that URI points to your existing listing template:

return [
    'staff/<route_staffMember>/articles' => ['template' => '_listings/default'],
];

Then simply use the relatedTo parameter to alter which entries get listed. The template will have access to a variable called route_staffMember which you can use to fork logic between the filtered/non-filtered views. (I like to prefix these variables with route_ because when I look at the code 6 months later I always scratch my head wondering where this magic variable is being set!)

For example:

_listings/default

{% set staffMemberId = route_staffMember is defined ? craft.entries.section('staff').slug(route_staffMember).ids() : null %}
{% set entries = craft.entries.section('articles').relatedTo(staffMemberId).all() %}

{# ...or, if you're using pagination: #}
{% paginate craft.entries.section('articles').relatedTo(staffMemberId).limit(12) as pageInfo, entries %}


Iterate through all entries and count a specific value

Before we proceed, let me say that whilst the following will work, I personally think this is a poor use of Twig.

It's far better to collate this information in a simple plugin, rather than jumping through such hoops in your templates.

Caveats dispensed with, here you go:

{% set criteria = {
    section: 'exampleSection',
    limit: 20,
    with: ['categoryFieldHandle']
} %}

{% set categories = {} %}
{% set entries = craft.entries(criteria).find() %}

{% for entry in entries %}
    {% set entryCategories = entry.categoryFieldHandle %}
    {% if entryCategories|length %}
        {% for entryCategory in entryCategories %}
            {% set categorySlug = entryCategory.slug %}

            {% if categories[categorySlug] is not defined %}
                {% set categories = categories|merge({
                    (categorySlug): {
                        count: 0,
                        category: entryCategory
                    }
                }) %}
            {% endif %}

            {% set categoryCount = attribute(categories, categorySlug)['count'] + 1 %}

            {% set categories = categories|merge({
                (categorySlug): {
                    count: categoryCount,
                    category: entryCategory
                }
            }) %}
        {% endfor %}
    {% endif %}
{% endfor %}

{% if categories|length %}

Category Counts

        {% for categoryKey, categoryInfo in categories %}

{{ categoryInfo.category.title }}: {{ categoryInfo.count }}

        {% endfor %}

{% endif %}

Note that we're eager loading the categories. Otherwise, we'll end up with N+1 queries.


Get categories ordered by the associated entries' postDate

You could technically do this with a lot of custom SQL, but it would be messy. I think your best bet would be to create a custom Date field on your categories called “Last Used”, and then to write a module that keeps its value updated as entries are saved.

The default Craft 3 project comes with a module file out of the box, so you can use that as a starting point.

First, add this to the top of the module file, after the namespace line:

use Craft;
use craft\elements\Category;
use craft\elements\Entry;
use craft\events\ModelEvent;
use yii\base\Event;

Then in its init() method, add this after the parent::init() line:

Event::on(Entry::class, Entry::EVENT_AFTER_SAVE, function(ModelEvent $event) {
    /** @var Entry $entry */
    $entry = $event->sender;

    if ($entry->enabled) {
        // Loop through the related categories
        foreach ($entry->myCategoriesField as $category) {
            /** @var Category $category */
            // Is this entry's post date more recent than the current Last Used value?
            if ($entry->postDate > $category->lastUsed) {
                $category->setFieldValue('lastUsed', $entry->postDate);
                Craft::$app->elements->saveElement($category, false);
            }
        }
    }
});

You can get Craft to re-save all of your entries by re-saving each of your sections’ settings. (You don’t need to change anything.)

With that in place, you can start sorting by that custom field in your templates.

{% set categories = craft.categories()
    .group('myCategoryGroup')
    .lastUsed('not :empty:')
    .orderBy('lastUsed desc')
    .limit(4)
    .all() %}


Is it possible to filter entries based on entry table field values?

OK, one possible way is the use the value of the colour field in an if statement, something this:

{# list rows that have "blue" in the colour field #}
{% for row in table.fieldName %}
{% if row.colour == 'blue' %} // probably best to make "blue" a variable
    <li>{{ row.age }} - {{ row.provider }} - etc.</li>
{% endif %}

In order to sort the table by a field value you will have to create a new array with the table data, then order by the name value. Will work that up for you in a bit

You could also do it with JavaScript, but that is nasty.

Here is the complete code using an Array to sort by the age field:

{% set tableBlock = [] %}
{% set tableRow = [] %}

{% for row in entry.myTableField %}
    {% if row.colour == "blue" %}

    {% set tableRow = {
        'age' : row.age,
        'colour' : row.colour,
        'provider' : row.provider
    } %}
{% set tableBlock = tableBlock|merge([tableRow]) %}
    {% endif %}

{% endfor %}

{% for row in tableBlock|sort %}
    {{row.age}} {{row.colour}} {{row.provider}}
{% endfor %}

For some reason the code block formatting is not working...


loop through an entry's "related entries", grouped by category

Try this:

{% for category in categories %}
    <h2>{{ category.title }}</h2>{# spit out the Category #}

    {% set entries = craft.entries.section('news').relatedTo(category) %}
    {% for relatedEntry in entries %}
        {{ relatedEntry.title }}
    {% endfor %}
{% endfor %}

See the set entries = ... line.

I am retrieving the entries that are related to each category as it loops thru each category.


If i'm understanding this correctly, it looks like you just have your loop starting a little early in the markup, so at the moment you are creating a new
 item for every entry.

Does moving the {% nav entry in entries %} loop within the first
 help at all? like this:

 {% nav entry in entries %}

        {{ entry.title }}
        {% ifchildren %}

               {% children %}

        {% endifchildren %}

 {% endnav %}

Additionally

Whilst writing this answer out I noticed that your {% endifchildren %} tag comes before a closing
 tag, so it might just be that:

     {{ entry.title }}
     {% ifchildren %}

              {% children %}

          {# endifchildren was originally here #}

     {% endifchildren %}


Change default status of entry publication (Lightswitch 'Status')

If you're using a Craft Client or Craft Pro, you can save your entry as a draft and review it later.

This isn't foolproof either. If you wanted to really try to restrict yourself, you could set up another user account that doesn't have privileges to "Publish live changes."

But again, this would require either a Craft Client or Craft Pro license.


I cannot get the email address to properly update from my user account management form

As of Craft 2.3, the rules for changing an existing password are:

If you're editing your existing account OR you're an administrator OR you have the 'changeUserEmails' permission set on your user account, then you need to supply your existing user account's password as a hidden input (not the current password for the account you're trying to change).

<input type="text" id="currentPassword" name="password" />


Get all URLs from a multisite installation

I don't know what version of Craft you're using, but recently it became possible to request multiple site's version of the same entry/entries. For this to work, you need to provide multiple site ID's to the siteId part of the query, or multiple handles to the site part of the query:

{#
 # Provide the entry element query with the IDs for 3 sites
 # and group those by the entry's ID, so we know which entries belong together
 #}
{% set entriesById = craft.entries.siteId([1,2,3]).all() |group('id') %}

{#
 # Loop through the grouped entries and display whatever you need to display.
 # Each entry has their own `siteId` set, so you can use .getUrl() (or .url) to display the url
 #}
{% for entryId, entries in entriesById %}

Entry {{ entryId }}

    {% for entry in entries %}
        URL: {{ entry.url }} - Status: {{ entry.status }}
    {% endfor %}
{% endfor %}

If you are using Craft 2 (or a Craft 3 version before it became possible to query multiple site's entry versions at once), I think you could do it like this:

{# Craft 2 (untested, it's been a while ... #}
{% for locale in craft.i18n.getSiteLocales() %}
    {% set entry = craft.entries.id([your entry's id]).locale(locale) %}

    {% if entry %}
        URL: {{ entry.url }} - Status: {{ entry.status }}
    {% endif %}
{% endfor %}

{# Craft 3, before my original answer became possible #}
{% for site in craft.app.sites.allSites %}
    {% set entry = craft.entries.id([your entry's ID]).siteId(site.id).one() %}

    {% if entry %}
        URL: {{ entry.url }} - Status: {{ entry.status }}
    {% endif %}
{% endfor %}


The default URL to access Craft is /admin.

Note also this can be changed to anything you like using the cpTrigger config variable.


How to return errors from a model back to the template?

If you use $model->getErrors() instead, it should return a multidimensional array of errors indexed by attribute name like so:

array(
    'email' => array(
        'First email error.',
        'Second email error.',
    ),
    'firstName' => array(
        'First firstName error.',
    ),
);

Or you can get errors specifically for an attribute like so:

$model->getErrors('email');

Then update the template to check for the errors, since it is now a multidimensional array that's returned.

{% if errors.email is defined ? errors.email | length %}
<div data-alert class="alert">
    {% for error in errors.email %}
        {{ error }}
    {% endfor %}
</div>
{% endif %}


How to exclude a page from the navigation tree

Use a descendantOf parameter with a new ElementCriteriaModel instead of the getDescendants method on your entry model and you can add additional parameters. In your case add cf_hideFromNav as a parameter:

{% set topEntry = craft.entries.section('pages').slug('club').first() %}
{% set navItems = craft.entries.section('pages').descendantOf(topEntry).cf_hideFromNav('0') %}

{% nav navItem in navItems %}
    ...
{% endnav %}

You could also use the parameters id or slug to exclude certain entries:

{% set topEntry = craft.entries.section('pages').slug('club').first() %}
{% set navItems = craft.entries.section('pages').descendantOf(topEntry).id('and, not 23, not 40, not 12') %}

The descendantOf parameter also takes IDs. This would allow you to do this all with just a single ElementCriteriaModel:

{% set navItems = craft.entries.section('pages').descendantOf('1').id('and, not 23, not 40, not 12') %}


Using the CP login session expiration for the frontend

What you want is this:

// Returns how many seconds are left in the current user session.
// (int) The seconds left in the session, or -1 if their session
// will expire when their HTTP session ends.
craft()->userSession->getAuthTimeout()

You can then combine this with a Javascript setTimeout when the page loads so you can trigger whatever messages you need.

Edit: You can use this in your template files:

{% set authTimeout = craft.session.getAuthTimeout() %}


Using a Sprout Form within a Sprout Form?

There is no default way to add a form within a form in Sprout Forms. Your proposed manual solution seems like a decent approach, but whenever you change a question on an existing form you will also be altering the historic data in any of your reports.

A two-forms approach

A more straightforward approach may be to make your process two forms. Have a primary form that has the core questions that don't change and a second form that the users are directed to for the questions that do. You could use a Form Relations as a Global Field or on a particular Single to assign which secondary form was needed and should be able to link between the submitted entries by tracking the IDs via a Sprout Fields Hidden Field or developing a custom front-end field that created the relationship in a more user-friendly way.

Using two forms will help you maintain accurate historic data and stick within existing functionality which will likely be easier to maintain in the long run.

A custom field approach

More speculatively, you could potentially develop a custom plugin and custom field that help you do this. It would definitely require a bit of planning, and I probably would vote against going this route, but to highlight some of the challenges you would face, here are some initial thoughts on what that might look like:

The fields that change would probably need to store data in a similar way. If all the fields that needed to change were Plain Text fields, that will likely be much easier of a problem to try to solve than if you need to swap questions that relate to different types of fields. It will likely be easier if the number of questions also stayed the same.
Sprout Forms stores fields locally to each form created, so you would not be able to use the Field Settings to control global attributes, you would need a separate custom field plugin settings area where you could control settings, such as the labels of the questions that change, across all instances of where the fields are used.
You'd probably also run into some challenges on how to create reports on the historic data. If answers to the questions of the first month relate to different questions than the answers to the data of the second month, you'd also have to find a way to store the questions that were being answered as part of the form submissions to know what the responses were actually referring to.


Possible to change style of password reset page

Set the setPasswordPath config setting to a template in your craft/templates folder and you style the page however you want.

The form itself would need to be similar to the "Set Password Form" template example in the docs.


How can I get the same element ids that the DeleteStaleTemplateCaches Task ends up with before the element has saved?

This is not much of an answer but basically Brad was right - I just needed to replicate the logic that the DeleteStaleTemplateCachesTask does in its getTotalSteps() and runStep() methods.

This allows you to work out exactly what caches will be just about to be deleted. I'm not going to post the code here as it is literally a copy/paste from the DeleteStaleTemplateCachesTask.


Going to mark this as off-topic (Craft issues should be posted to https://github.com/craftcms/cms/issues, which I realize is a bit ironic to tell you considering you said you don’t want to use Git, but you don’t need to use Git to open a GitHub account).

That said, the issue is that Craft 3 uses Composer behind the scenes to install plugins and update itself right now. So even though you don’t need to directly interface with Composer now that the zip option is available, the system you are running on must at least be able to run Composer. And Git is a requirement of Composer.

For this and other reasons, we are planning on making Craft 3 less reliant on Composer in a future update.

  After installing on my local Mamp setup it's not obvious which files I need to upload to the live server as there isn't a plugin folder.

You need to upload the entire vendor/ folder.

  Does this mean that I won't be able to use Craft now unless I become a command line expert?

As long as your system is capable of running Composer (which it sounds like you’ve taken care of), no you shouldn’t need to run any commands from the terminal yourself.

  Even the Mijingo video tutorials which have been really easy to follow in the past have started to be full of complicated command line stuff.

Up until the Craft 3 GA launch on April 4, the only way to install Craft 3 was via the terminal. Now that a zip download is available from https://craftcms.com, that’s not the case anymore.


How to fetch only selected child category?

I'm not really sure why craft is working that way and I'm not really sure if my way is the intended to solve it but it works at least for me. Make sure you select the one that fits best for you. Usually the best is the third one.

First solution
If you have a limitation in your field how many categories you can link the .last() function would suit since your child is always the last element and your parent is the first one.

{% set category = entry.fieldHandle.last() %}

But this does not work if you are going to relate multiple Cateogies

Second Solution
If your selected categories are always at level 2 and never at level 1 you can do the following. This works for multiple categories as well

{% set categories = entry.fieldHandle.level(2).all() %}
{% for category in categories %}
    {{ category.id }}
    {{ category.title }}<br>
{% endfor %}

Third solution
Change your matrix structure into two different channels (countries and continent) and relate your continent with your countries. In your relation field you restrict the selection to those two groups.
That way a user can select the country and/or a continent individually.


There isn't really a good way to extract large chunks of Craft entries using the core features in Twig. Every entry you fetch is a EntryModel and those take up some memory due to relations and other stuff in Yii's ActiveRecord class.

What you can do is to create your own custom Plugin that does the same thing but queries the database directly instead, by-passing Crafts EntryModels and just giving you the dataset results directly.

Here's some resources on getting started with Plugin development:

Craft official documentation: https://craftcms.com/docs/plugins/introduction

From StraightUpCraft: https://straightupcraft.com/plugin-development

A wrapper for creating a Plugin default setup: http://pluginfactory.io/


Is there a way to limit output of Tags related to an entry?

A limit doesn't make sense on a single element model. But all ElementCriteriaModels have a limit parameter and for craft.tags it is documented here.

To limit the tags related to an entry via a Tags field don't use the shortcut syntax:

{% set tags = entry.tagsFieldHandle %}

But modify the craft.tags ElementCriteriaModel instead:

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


Sprout Forms - An unknown error occurred when trying to view entries in CP

You're experiencing two different things.

First, as Johannes suggested, if you update to the latest version of the plugin (using the same url that you were sent for the private beta), the error in the control panel will be fixed.  This issue was introduced in Craft 2.3 and was resolved in Sprout Forms 0.8.3

Second, it sounds like you have some issues with Email Notifications.  Assuming you have all the Form Notification settings in place and functioning email, as it sounds like you do, we recently discovered a bug where email notifications are not sent if you are using ajax to submit your forms.  We have a fix we can send you, and it should be resolved once we have a chance to release that and a few other fixes in Sprout Forms 0.8.4

Please send us a note if you have any more questions and we'll get you the updated file if you need it before we get those updates into the next release.

Ben


How can I get/check the contents of a cart via javascript (cookie)?

The cookie that Craft Commerce uses for cart/session management is set using Craft's craft()->userSession->saveCookie, which hard-codes cookie's httpOnly flag, meaning it can't be accessed by JavaScript.

If you want to pull of what you're trying to do, you'll need to use something like the LJ Cookies or Cookies plugin to add and ready your own cookie according to your business logic.


Not sure why you are escaping the / right in front of the regex. Maybe thats the issue?


How can I add data from my custom plugin to the Entry Listing table?

It will take two hooks in the MyCustomPlugin.php file to display data from the custom field.

public function modifyEntryTableAttributes(&$attributes, $source)
{
    if ($source == '*')
    {
        unset($attributes['expiryDate']);
        $attributes['whatever-you-want'] = Craft::t('Desired Table Heading');
    }
}

The modifyEntryTableAttributes() hook will allow us to add/remove columns from the Entries Listing table. Note that the $attributes[] variable will automatically try to match up whatever you put in there with an attribute on the entries.

This is probably all you need to drop a standard custom field into the table. However, since my custom field is an array, holding multiple bits of data, we need to use the getEntryTableAttributes() hook to dig in to my custom field and grab the item we want to display.

public function getEntryTableAttributeHtml(EntryModel $entry, $attribute)
{
    if ($attribute == 'whatever-you-want')
    {
        // Assign my custom field to a variable
        $fieldData = $entry->mycustomfield;

        // Check if there is any data in the variable
        if (!empty($fieldData)) {

            // If so, return the specific key AS A STRING to the table
            return $fieldData['myCustomDate']->format('n/j/y');
        }

        return '';
    }
}

Notice the return ''; at the end? That's important, because if an entry DOESN'T have my custom field attached to it, it will try to look up the $attribute['whatever-you-want'] assuming that's a legitimate DB column, and will fail.


Shortest code to link to CSS and JS file

In Craft there's {% includeJsFile %} and {% includeCssFile %} which get injected on the getHeadHtml() and getFootHtml() functions on your templates.


How do you customize what value a Custom FieldType returns to a template

Run your HTML string through getRaw before sending it back to the template...

return TemplateHelper::getRaw($output);

This will basically "pre-raw" your HTML string.


Running Craft with Docker (or something similar)

I am creating an image to help me test Craft.

https://github.com/gabrielmoreira/docker-craft


Guest Entries plugin will only submit when logged in - not anonymously (via AJAX)

So can now answer this myself. Basically the issue is the CSRF token validation.

Options are to disable CSRF in the config.php file. Up to you how comfortable you are with that.

Or use the CSRF token properly! I thought I could set the token statically but that's not the case (which is obvious in hindsight). It is unique to each browser and is set as a cookie.  To work with a pure JS set up this needs be set dynamically as a JS variable on page load. More information here: https://craftcms.com/support/csrf-protection#updating-your-javascript


How can I retrieve Users of a specific User Group with GraphQL?

This is not possible on Craft 3.3.x but group and groupId have been added since 3.4.0-beta.5 (commit)

With the update, you can do:

query getAllUsers{
  users(groupId:1) {
    id,
    username
  }
}

Or:

query getAllUsers{
  users(group:"groupHandle") {
    id,
    username
  }
}


From what I understand you can use the one licence key on multiple
  environments but you can only then login to the Admin area from one of
  them?

Sort of – you'll be able to login everywhere, but if the license isn't valid the CP will be blocked behind a "upgrade-wall", prompting you to purchase a valid license or downgrading to Personal (the free edition). The frontend will continue to function as normal, though.

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

Yes. From the docs:

  You’re allowed to run a single Craft license on multiple domains (e.g.
  example.com and example.fr), so long as they’re all a part of the same
  website. In order to enforce that, Craft does have one technical
  limitation: you may only access Craft’s control panel from one public
  domain per Craft license. (There is no such restriction on non-public
  domains, though.)

One of the ways Craft determines if the domain is non-public, is if the site has a dev-sounding sub domain (e.g. dev, local, stage, or staging). This means that a Client or Pro license registered to www.mysite.com should also work for a staging site at http://stage.mysite.com.


Rich Text fields always return the paragraphs wrapped in <p> tags. So you would have to use an additional <div> element and apply the dropcap styles to the first <p> tag within that <div> using the first-of-type pseudo-class.

<div class='dropcap'>
    {{ entry.body }}
</div>

.dropcap p:first-of-type:first-letter {
  float: left;
  font-size: 4em;
  line-height: 3em;
}


I receive a prompt that my login credentials are incorrect, even though I am sure I have them set to the correct value.

If you're sure they're correct, then maybe Craft is connecting to a different database/Craft installation on the server than the one you think it's connecting to?

If you have access to the database, you can check to see if your user exists in the craft_users table and you can manually force a password reset like so: https://craftcms.stackexchange.com/a/13966/57


Events are generally not capable of having an effect on the calling code; they’re just notifications.

You would probably be better off disabling public user registration (Settings > Users > Settings), and creating a custom controller that registers users instead. Your controller would be the one to determine if there are still any slots left, and if so, call craft()->users->saveUser() itself.


You can use the HttpRequestService:

craft()->request->redirect($myAwesomeUrl);


The original poster solved this in a follow-up comment:

  After checking the log file - see my other question -, i activated the php functions "proc_open" and "proc_close" at my hoster's php settings and it worked. I'm not sure if i can leave these settings.

proc_open and proc_close are required if you want Craft 3 to automatically backup your database because it uses the native mysqldump and pg_dump binaries to perform the backup.

If, for whatever reason, you can't enable those methods, your options are to:

Set the backupCommand config setting to false. This will prevent Craft from performing database backups and you'll be responsible for manually creating them.
Set the backCommand config setting to some other script or service that can perform a backup without using those disabled methods.  Craft will respect whatever is set in this config setting.


You could query for your two blocks individually.

{% set quoteBlock = entry.intro.type('quote').first() %}
{% set textBlock = entry.intro.type('text').order('RAND()').first() %}

{{ quoteBlock.quote|raw }}

    {{ quoteBlock.caption }}

{{ textBlock.column1 }}

{{ textBlock.column2 }}


You could add a field "IP Address" to your Entry Type and make the form submit the guest's IP (→ getIpAddress() method) via a hidden field.

<input type="hidden" name="fields[ipAddress]" value="{{ craft.request.getIpAddress() }}">

For further improvements you could make your own field type for "IP Address" with a plugin, that adds custom validation (→ block certain IP ranges). You could also hide the field from the CP or make it only readable.


Is it possible to show commerce product id's in the control panel?

No, it does not seem to be possible to select the ID as column to be shown in product overviews when clicking on the cogwheel on the left side.
You could use this extension https://plugins.craftcms.com/preparse-field to create a custom field into which you can "preparse" the product's ID. This field will then be available for selection.


Exception on trying to install Craft CMS 3 plugin

Please remove the first \ and include a vendor directory

11 namespace [package]\[websitename];
12
13 use [package]\[websitename]\variables\[websitename]Variable;

The namespace must always consist the package and the plugin name docs

Here is an example

namespace ns\prefix; // <-- see: ns\prefix, not only prefix

class Plugin extends \craft\base\Plugin


How do you set an "If" option on an entry that includes "contains"

OKay so the solution I found is this. It was much more complicated than I wanted it to be but it works.

{% set VARIABLE = 0 %}
{% for entry in craft.entries.section('ENTRY') %}
    {% if entry.FIELDNAME.contains('CHECKBOX OPTION') %}
        {% set VARIABLE = VARIABLE + 1 %}

CONTENT

    {% endif %}
{% endfor %}
{% if VARIABLE <= 1 %}

CONTENT

{% endif %}


The whole plugin API has gotten an overhaul in Craft 3, so all plugins needs to be rewritten/updated to work with Craft 3.

Craft Commerce hasn't been updated yet. If it had there would be separate versions for Craft 2 and 3 for download.


Any working RSS feed examples out there?

Here's the boilerplate I've been using for RSS feed templates. I just name the file rss.html and call it a day.

This assumes a channel is set up with a description and title field.

{% header "Content-Type: application/rss+xml" %}
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">

{% set rss = craft.entries({ section: 'yourChannel' }) %}

<channel>
  <title>Title Your RSS Feed</title>
  <link>http://www.yourlink.com/</link>
  <description>Enter a description here</description>
  <language>en-us</language>
  <atom:link href="{{ url() }}" rel="self" type="application/rss+xml" />

  {% for item in rss %}
  <item>
    <title>{{ item.title }}</title>
    <link>{{ item.url() }}</link>
    <description>{{ item.description }}</description>
    <pubDate>{{ item.postDate.rfc2822() }}</pubDate>
    <guid>{{ item.url() }}</guid>
  </item>
  {% endfor %}
</channel>

</rss>


Saving a "craft-linkfield" field via an entry form

Found a solution by inspecting the HTML for the entry edit form in the CP. This works:

<input id="fields-website-type" name="fields[website][type]" value="url" type="hidden">
<input id="fields-website-isCpFormData" name="fields[website][isCpFormData]" value="true" type="hidden">
<input id="website" type="text" name="fields[website][url]">


How do I output entries by their category?

It might be quicker to turn it around: first get all the entries you need, then group those by their category:

{% set entries = craft.entries.section('people').find() %}

{% for category, catEntries in entries | group('categoryFieldHandle.first().title') %}

{{ category }}

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


Available updates not displaying on local copy but show up on live site; instead displays "You're all up to date!" with 5 pending updates

Adding my comment as an answer because it fixed my issue:

I traced the issue to a deprecation warning involving $HTTP_RAW_POST_DATA being populated.

I added the line always_populate_raw_post_data = -1 to my fpm_app.conf which solved the issue.


How do I reference the settings of my plugin?


Duplicate of https://github.com/putyourlightson/craft-sprig/issues/118
The code is correct and what you are experiencing is likely due to local browser caching.


check if a route segment matches a section entry type

Take a look at the {% exit %} tag. You should be able to do something very similar, since your search will return no results if the entry type does not exist.

{% set entries = craft.entries.type(craft.request.getSegment(3)).relatedTo(category) %}

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


Craft site has the excellent document How do I list the entries related to a category?

Building on that, you would fetch your category (by slug), and then the entries related to the category.

{# Fetch the category with slug 'categorySlug' #}
{% set category = craft.categories.slug('categorySlug').first() %}

{# Fetch all of the entries related to this category #}
{% set entries = craft.entries.relatedTo(category) %}

Then loop over those entries.


How to write a segment that is not two other segments

I personally try to avoid inlining too many conditionals because I feel like it leaves room for logical loopholes. I also think using variables for segments keeps things easier to read.

{% set seg2 = craft.request.getSegment(2) %}
{% set seg3 = craft.request.getSegment(3) %}

So maybe something like this? The keyword in is Twig's way of checking in_array()

{% set badItems = ['itemA', 'itemB'] %}

{% if seg2 == 'Subcategory' %}
    // do top priority thing
{% elseif seg3 != '' and seg3 not in badItems %}
    // do secondary thing
{% else %}
    // do overall default thing
{% endif %}

However, if you know the finite list of acceptable items beforehand, I think this is more concise.  Since segment 3 could be blank if it's not there, maybe try checking if it is something instead of if it's not something.

{% set goodItems = ['itemC', 'itemD'] %}

{% if seg2 == 'Subcategory' %}
    // do top priority thing
{% elseif seg3 in goodItems %}
    // do secondary thing
{% else %}
    // do overall default thing
{% endif %}


Define a dynamic 'basePath' environmental variable without the locale

Check out craft-multi-environment; even if you don't use it, you might crib some of the ideas from it.

For instance, how the basePath is determined.


I don't think the ternary operator does what you want it to do. According to this page, the first part of your URL format would return 1 (true) if the parent uri is not __home__, or an empty string if it is.

You could try:

{ parent.uri != '__home__' ? parent.uri }/{slug}


High volume category list causes slow load

This is a known issue with category and structured section UI in the control panel.

Performance actually starts degrading around the 3-400 item mark, but it will be addressed in the upcoming 2.2 release.


How to load entries with a certain category only?

You could use this, note: this is untested maybe you have to remove the first() or use targetElement: category1.id

{% set category1 = craft.categories.id(yourId).one() %}
{% set category2 = craft.categories.id(yourId2).one() %}
{% set news = craft.entries.all({
    section: 'news',
    relatedTo: [
        'and',
        { targetElement: category1.id },
        { targetElement: category2.id }
    ]
}) %}

You should read about that topic here click


This burned me awhile back. As I understand it, your code is not just running 44 times, it's actually running an endless loop... until it blows up (and likely runs out of memory).

Basically when you attach onto onSaveUser and then save again using SaveUser, Craft is going to give other plugins—that also latch onto the onSaveUserevent—a shot at manipulating the data you just saved.

So the wrinkle there is Craft is going to call your code again, resulting in the endless loop. Basically you need a way to break the loop.

Brad mentions  one way around that is to simply update the db directly instead of calling saveUser. Since you're using a custom field, that's a bit harder to do.

Another would be to define a static variable and only allow your code to call saveUser once.

public function init()
{
    craft()->on('users.onSaveUser', function (Event $event)
    {
        $user = $event->params['user'];

        if ($user->talentJobFamily->value != '') {
            $user->getContent()->setAttributes([
                'talentStage' => 'engage',
            ]);

            static $recursionLevel = 0; // is set only once

            if ($recursionLevel == 0)
            {
                $recursionLevel++; // saveUser only gets called once
                craft()->users->saveUser($user);
            }
        }
    });
}

That's also documented in my original question.


Nevermind - had a typo in my template code. Using "descendantOf" works as advertised!


Craft 3 Image quality is terrible after asset upload from admin panel

Converting my comment(s) into an answer...

Make sure you are using the ImageMagick library to handle image manipulation (instead of the default GD library). It provides much better results.

Craft will "clean" every image that gets uploaded. This prevents anyone from accidentally (or intentionally) uploading malicious scripts to your site hidden within an image file.


How can I make my custom FieldType show up in an element index?

To make it possible to select fields from a custom FieldType in the Customizable Element Indexes interface, your FieldType class needs to implement the IPreviewableFieldType interface, like this:

class ExamplePluginHandleFieldType extends BaseFieldType implements IPreviewableFieldType
{
    ...

If you want to modify how the values from your custom FieldType displays in element indexes, you need to add a getTableAttributeHtml method to your FieldType class:

public function getTableAttributeHtml($value)
{
    return $value ? $value->id : null;
}


Moved Craft 3 site to new server and getting "No primary site exists" error

I was able to resolve this issue by reimporting the database.


This is probably not the answer you are looking for but it works. You can change the Craft.BaseElementIndexand the updateElements function. All you have to do is to change the destination path to a custom controller

Craft.BaseElementIndex.prototype.updateElements = function()
{
    // Ignore if we're not fully initialized yet
    if (!this.initialized)
    {
        return;
    }

    this.setIndexBusy();

    var params = this.getViewParams();

    Craft.postActionRequest('yourPluginHandle/controllerName/getElements', params, $.proxy(function(response, textStatus)
    {
        this.setIndexAvailable();

        if (textStatus == 'success')
        {
            this._updateView(params, response);
        }
        else
        {
            Craft.cp.displayError(Craft.t('An unknown error occurred.'));
        }

    }, this));
},

Then you can create a custom controller that extends the ElementIndexController and can use it's function that calls the private function _getElementResponseData. All the elements that should be displayed are received in

$responseData['html'] = $this->_elementType->getIndexHtml(
    $this->_criteria,
    $disabledElementIds,
    $this->_viewState, <-- this is the important variable
    $this->_sourceKey,
    $this->_context,
    $includeContainer,
    $showCheckboxes
);

The sort order is defined here

if ($sortableAttributes)
{
    $order = (!empty($viewState['order']) && isset($sortableAttributes[$viewState['order']])) ? $viewState['order'] : ArrayHelper::getFirstKey($sortableAttributes);
    $sort  = (!empty($viewState['sort']) && in_array($viewState['sort'], array('asc', 'desc'))) ? $viewState['sort'] : 'asc';

    $criteria->order = preg_replace('/^(.*?)(?:\s+(?:asc|desc))?(,.*)?$/i', "$1 {$sort}$2", $order);
}

As you can easily see it checks if the $viewState['order'] is empty or not. This variable is defined in your controller so all you have to do is to check if your javascript returns a order variable, get the field by handle and check if the field handle is instance of BaseRelationField. If so, you'll unset the variable in the $viewState and change the $criteria by yourself.

Unfortunately the query is executed in BaseElementType.php so you have to implement a way to sort by eager loading elements (which I doubt is possible by default) or you can create a custom element type just for this case and overwrite the entire getIndexHtml() function.

It might sound like a lot of work and effort but honestly it can be done in 5-10 minutes... I've done the same once within no time. It's 99% copy paste. Maybe someone  has a better answer but since there is no real event or hook I'm not sure if there is a real clean way to do this. Of course this is only for Craft 2. In Craft 3 it's much easier since there are more events and hooks and you can replace classes more easy.

Another approach would be to overwrite the entire BaseElementIndex class with Yii or this. But I never did that so I can't give much advice


As André pointed out, you only need to run the installer if you need Craft to create all of the necessary tables in a blank database.

If you've dumped your database from dev/staging and imported it into production, there is no need to run the installer, because the tables are already there.

If Craft sees someone try to load the installer on a site that already has a populated database like you have, it will return a 404.


Using field types to override meta defaults

To override the Default meta data with your field type the only addition you need in your code is to pass the entry.id to your craft.sproutSeo.meta tag:

{% do craft.sproutSeo.meta({
    id: entry.id,
    default: 'default',
    title: entry.title,
    description: entry.body|striptags|slice(0, 160)
}) %}

Once you identify the entry.id Sprout SEO will handle the rest, prioritizing any values you have in your field types above any values in your Defaults or Code Overrides.


I don't think this will exactly answer your question, but I think it will help get you going in the right direction.

Within my application, I am grabbing entries that belong to the currently logged in user - finding the fields and then displaying an average distance.

If you'll notice I am setting a level': 2 in my parameters. That's because I am working with a structure and the first level is the "parent" entry that does not have any of the data I am attempting to average.

{# Get all of the entries entered by the user. #}
{% set entries = craft.entries({
    'section': 'mySection',
    'level': 2,
    'descendantOf': user.id
}) %}

{% if entries|length %}

    ...

    {% set value = 0 %}
    {% set count = 0 %}

    {% for entry in entires %}
        {% set value = value + entry.distance %}
        {% set count = loop.index %}
    {% endfor %}

    {% set averageDistance = (value / count)|round(1, 'floor') %}

Avg: {{ averageDistance }}

    ...

{% else %}
    {# Could not find any entries. #}
{% endif %}

So in a nutshell, you'll want to:

grab the entries from the appropriate section
find the field(s) you want to average ex: distance
do math
return the result

For you (this is a stab in the dark) you would want to get all users, get the value of the age field. Then loop over to get your count and divide that by the ages.

Hope this helps!


The query value for p has been the pageTrigger since Craft 1.0 (and probably in the beta as well).

I'm not sure why you were still able to use it for other purposes up until recently. To be honest, it sounds like you were accidentally exploiting a bug, which has since been fixed.


Any way to manually generate a transform on an asset source?

You could just make a temporary template that makes Craft generate them for you. And depending on how many these are, you better use limit and offset with your craft.assets call.

{% set images = craft.assets.source('myAssetSource').limit(50).offset(0) %}
{% for image in images %}
    <img src="{{ image.url('fullwidth') }}">
{% endfor %}


As Douglas mentioned in the comments, if the relation is defined within a Matrix block, then the Matrix block is the source of the relation; not the entry.

Soy you just need to change relatedWorks and relatedPerformers to:

{% set relatedWorks = craft.entries.section('Works').relatedTo(block) %}
{% set relatedPerformers = craft.entries.section('Performers').relatedTo(block) %}


Can I eager load Super Table fields in a Matrix block?

This appears to have been added in the 0.4.7 release!

View the original issue here.

Note: I have not personally verified this functionality.


Can guests upload files to assets in an entry form?

I just tested this locally and it's working fine (with the caveat that the latest build 2.1.2568 introduced a separate, unrelated bug that broke front-end asset uploading that's been fixed in build 2.1.2569).

Most likely something is failing validation when the entry is saving.

Try using this to see if there are any errors:

<form class="ajax-form" method="post" action="" enctype="multipart/form-data" accept-charset="UTF-8">

    {% macro errorList(errors) %}
        {% if errors %}

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

    <input type="hidden" name="action" value="guestEntries/saveEntry">
    <input type="hidden" name="sectionId" value="17">
    <input type="hidden" name="enabled" value="1">
    <input type="hidden" name="fields[whitepaperCategory]" value="{{entry.title}}">

    Name
    <input type="text" id="name" name="title" required>

    {% if entry is defined %}
        {{ errorList(entry.getErrors('title')) }}
    {% endif %}

    Email Address
    <input type="email" id="email" name="fields[email]" required>

    {% if entry is defined %}
        {{ errorList(entry.getErrors('email')) }}
    {% endif %}

    Resume and Cover Letter (.pdf)

        Upload Resume and Cover Letter
        <input type="file" id="resume" name="fields[resumes][]" class="upload" multiple>

    {% if entry is defined %}
        {{ errorList(entry.getErrors('resumes')) }}
    {% endif %}

    <button type="submit" class="btn btn-submit">Submit</button>
</form>


Rename Entries to Content on CP top menu

For custom "cosmetic" changes on the Control Panel there's these two Plugins by Lindsey DiLoreto:

Control Panel JS
Control Panel CSS

.

You can do both, hiding and renaming of menu items with CSS:

#nav-dashboard {
  display: none;
}

#nav-entries a,
#nav-entries a:hover,
#nav-entries a:active {
  color: transparent;
  word-spacing: -9999px;
  letter-spacing: -9999px;
}

#nav-entries a:after {
  content: "Content";
  color: #d7d9db;
  word-spacing: normal;
  letter-spacing: normal;
}

#nav-entries a:hover:after,
#nav-entries a:active:after {
  color: #fff;
}


Can you increase the max size of Rich Text fields?

Under your Rich Text field's setting, there is a "Column Type" option that's set to text by default, which will hold about 64k worth of data.  You can change it to mediumtext, which will store about 16M worth of data.


How can I separate assign user groups and permissions for users?

Non-admin users cannot change permissions for Admin users.

However, I agree with what you've said on users being able to assign groups and permissions. On practically every site I build, I need the client to be able to assign users to the groups that I created, but not be able to change a new user's permissions manually. This should definitely be separated in to two different options in the control panel.

UPDATE: In 2.6.2996 Craft added this functionality:

The “Assign user groups and permissions” permission has now been
split into “Assign user permissions” and “Assign user groups”, and
the latter now has nested permissions for each of the user groups.
Users with the “Assign user permissions” permission are no longer
allowed to grant new permissions to user accounts that they
themselves don’t already have.


Plugin I created is asking for a license key

Craft checks only the handle of your plugin to detect license mismatches. So when your plugin has the handle importer and another plugin in the store has the same handle it will mark it. (since importer is already a plugin in the store it's likely the issue)

The only ways to solve it

change your handle to data-importer or whatever might be unique
make a module out of it
(include CSS to remove the message and ignore it)


Problems translating the default "Name" field on tags

I can confirm this is indeed the case (as of  2.1.2564). I don't know if it's intended behaviour or a bug, but I would wager the former.  I seem to recall somewhere learning that P&T made an explicit decision to not have tag Names be translatable.

As a workaround you could consider a tag custom field with a "translatable label" that you fill in for each language? Seems a bit lame. I'd probably opt for simply making the field itself translatable, and then binding separate tags for each language.


Setting user password on creation / without full admin rights

Currently there isn't a way to do what you're looking for from the control panel, even if a user has "Administrate Users" permissions.

In the control panel, only current administrators can change an existing user's email or password and they must supply their existing administrator password to do so.  And even administrators can't set an initial password for a user from the control panel.

On the front-end, if you're running Craft Pro and you've enabled public registration, a user can set an initial password from the public registration form.


In my tests the paragraphize setting did not seem to fully prevent paragraphs from being generated. Instead { linebreaks: true } seems to reliably convert all would-be paragraphs to <br> tags.

If you're really serious about sticking to single lines then you can go even further and block all forms of line breaks:

{
    deniedTags: ['br'],
    enterKey: false,
    pastePlainText: true,
    linebreaks: true
}

The only flaw with this seems to be that linebreaks still show up in the editor if they're pasted in, but they are stripped when the entry is saved.


Help debugging "An unknown error occurred."

https://github.com/craftcms/cms/tree/master-v2/src/services/UserSessionService.php#L325

The error is thrown when you don't have the permission to change/do something. Your file permissions do not matter it is about the permissions in craft. Are you not admin? Could you tell us if you are a normal user and don't have certain permissions? Maybe another member of your team changed something?

Do you have any plugins installed that have any hooks/events?
Do you have the latest Craft version?