404 on localized entries - Nginx I'm stucked with a 404 error on all my localized sub-directories.
It works fine for the homepage ( es. domain.com/es, domain.com/it ). Also urls in the main directory are behaving correctly. Example:
domain.com/products is fine domain.com/es/products is not.

I'm running Craft Pro on Nginx. Here is my general.php:

'siteUrl' => array(
        'en' => 'http://129.0.1.67/',
        'en_us' => 'http://129.0.1.67/us/',
        'de' => 'http://129.0.1.67/de/',
        'fr' => 'http://129.0.1.67/fr/',
        'it' => 'http://129.0.1.67/it/',
        'es' => 'http://129.0.1.67/es/',
        'tr' => 'http://129.0.1.67/tr/',
        'ru' => 'http://129.0.1.67/ru/',
        'zh' => 'http://129.0.1.67/zh/'
)

Here is my index.php file for subfloders

/**
 * Path to your craft/ folder
 */
$craftPath = '../../craft';

/**
 * Define Craft locales
 */
define('CRAFT_LOCALE', 'es');

/**
 * Define Craft Templates Path
 */
 $templatePath = '../../craft/templates';
define('CRAFT_TEMPLATES_PATH', $templatePath);

I'm assuming that my problem is with my NGINX configuration but I'm not confident with it.

    root /var/www/app;

    location / {
            try_files $uri $uri/ @rewrites;
    }

    location @rewrites {
            rewrite ^(.*) /index.php?p=$1 last;
    }

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
    }

Here is a Craft log in the browser console:

[12:46:33.764][error][exception.Craft\HttpException.404]
Craft\HttpException in /var/www/craft/app/controllers/TemplatesController.php:72
Stack trace:
#0 [internal function]: Craft\TemplatesController->actionRender('es/oil-news/pro...', Array)
#1 /var/www/craft/app/framework/web/actions/CAction.php(109): ReflectionMethod->invokeArgs(Object(Craft\TemplatesController), Array)
#2 /var/www/craft/app/framework/web/actions/CInlineAction.php(47): CAction->runWithParamsInternal(Object(Craft\TemplatesController), Object(ReflectionMethod), Array)
#3 /var/www/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#4 /var/www/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#5 /var/www/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#6 /var/www/craft/app/framework/web/CWebApplication.php(282): CController->run('render')
#7 /var/www/craft/app/framework/web/CWebApplication.php(141): CWebApplication->runController('templates/rende...')
#8 /var/www/craft/app/etc/web/WebApp.php(290): CWebApplication->processRequest()
#9 /var/www/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#10 /var/www/craft/app/index.php(62): CApplication->run()
#11 /var/www/app/index.php(67): require_once('/var/www/craft/...')
#12 {main}
REQUEST_URI=/es/oil-news/prova

Seems like I needed a bit more configurations for NGINX, something like

location /es/ {
    try_files $uri $uri/ @esrewrites;
}

location @esrewrites {
    rewrite ^/es/(.*)$ /es/index.php?p=$1? last;
}

for each locale.
Source: https://gist.github.com/cmalven/5cc95cce4e495d3a11df

Still not sure if there is a better option that avoids hard coding locales in NGINX config file.


Saving a "craft-linkfield" field via an entry form I'm editing an entry via an entry form as documented here:
https://docs.craftcms.com/v3/dev/examples/entry-form.html

How would I be able to save a link field that's using https://github.com/sebastian-lenz/craft-linkfield ?

I tried this:

<input id="website" type="text" name="fields[website]">

(where "website" is the handle of the link field) but that just throws a syntax error (in json_decode) at vendor/sebastianlenz/linkfield/src/fields/LinkField.php:112

It works fine for other  elements that use one of the built-in field types.

Is this even possible using the standard entries/save-entry endpoint? Or would I need to write a custom controller, and how so?

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]">


Link to a nested category I'm using a matrix field to allow the author to add products they can link to category pages, but my code:

{% for block in entry.transformerProductNavigation %}
 {{ block.transformer.one.title }}
{% endfor %}

outputs the parent category, can I somehow display the nested category – as you would if it was an entry field and nested entries?

This solves my problem:

{% for block in entry.transformerProductNavigation %}
{% set chosenCategory = block.transformer.last() %}

      {# set a variable – chosenCategory to the 'last' category ensuring any nested categories are accessible   #}
      {{ chosenCategory.title }}

{% endfor %}

Thanks to this answer: How to fetch only selected child category?.


How can I re-order the same order? I want to have a button on order information page when clicked the same order should be repeated. How can I put the same products again in the cart or simply re-order again?

This would probably require a plugin with a controller which you could post the order id to when clicking the button. Within the controller you could then query the database to get each line item and add it to the cart within a service if it is in stock and still enabled. The final step would then be to redirect to the basket or posted url.

The docs here should help you get started: https://craftcms.com/docs/plugins/controllers


Local vs Amazon S3 asset paths in multi-environment config I'm looking to pull assets from a local folder when developing locally, and an S3 folder when on staging/production.

Is this possible? It looks like no, but I'm hoping that's not the definitive answer: Multi-Environment S3 Asset Paths

It appears you can't alter the asset 'type'. However, I've seen configs (specifically, this one: https://designkarma.co.uk/blog/localization-multi-environment-setup-in-craft) that seem to use different urls for local vs s3 assets. That gets rid of the ability to set a cache duration and other s3 specific options, however.

Is the only real way to do this is to set CORS settings on the S3 folder to allow connections from a local development URL, and use that for local/staging, and another bucket/config for production?

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

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


Invalid KML file using Smart Map Plugin I'm using Smart Map for Craft 3 to develop this filterable map for Columbia, Missouri. Here's the staging site:
http://visionzerodev.org/map-alpha/
This works brilliantly. Huzzah.
Now, I also need to add a couple of KML layers to it.
Here's where I'm developing the KML proof of concept:
http://visionzerodev.org/map-bravo/
BUT — I get the this error: "Invalid KML file".
I'm sure I'm missing something obvious.
The KML is importable in Google Maps:
(It was previously used as is in FusionTables)
https://drive.google.com/open?id=1J4epYVJPZXFrmQjq19PSfQuMiTGWmcbt&usp=sharing
The KML file is publicly accessible here:
http://visionzerodev.org/assets/data/high-crash-network.kml
Here's my Twig:
  {% set kmlFile = '/assets/data/high-crash-network.kml' %}

  {% set options = {
    height: 600,
  } %}

  {% if kmlFile %}
    {{ craft.smartMap.kml(kmlFile, options) }}
  {% endif %}

I like where you're going with this, but what you're trying to do isn't possible (yet).
As it currently stands, you need to use an Asset as the kmlFile parameter...
https://plugins.doublesecretagency.com/smart-map/kml-files/
It's on the roadmap to allow a string URL to be passed in directly.

UPDATE:
I've just added the ability to specify a KML by its absolute URL string. The new feature will be included in the next release of Smart Map. :)


Return JSON array without extra square brackets I'm having difficulties to remove an additional set of square brackets or avoid including them within array.

My JavaScript code currently accesses array's object at 0 index and therefore I'd have to loop in one level deeper array. Which I'd like to avoid if possible.

This is my endpoint:

'pricelist/<entryId:\d+>.json' => function($entryId) {
    return [
        'elementType' => ElementType::Entry,
        'criteria' => [
            'section' => "products",
            'descendantOf' => $entryId,
        ],
        'transformer' => function(EntryModel $entry) {

            $products = [];
            // "orderItem" is entry field
            foreach ( $entry->orderItem as $product ) {
                $products[] = [
                    'title' => $product->titleVariation,
                ];
            }
            return $products;
        },
    ];
},

Returned JSON array is:

{"data":
    [
        [
            {
                "title": "a",
            },
            {
                "title": "b",
            },
            {
                "title": "c",
            }
        ]
    ]
}

Expected JSON array output:

{"data":
    [
        {
            "title": "a",
        },
        {
            "title": "b",
        },
        {
            "title": "c",
        }
    ]
}

I have almost the same scenario from this question but the answer wasn't my issue.

change $products[] = to $products = in your for each loop, that should fix the extra square brackets. And if you want to get all entries and their titleVariation fields you should use 'elementType' => Entry::Class

'pricelist/<entryId:\d+>.json' => function($entryId) {
    return [
        'elementType' => Entry::Class,
        'criteria' => [
            'section' => 'products',
            'descendantOf' => $entryId,
        ],
        'transformer' => function(Entry $entry) {

            $products = [];
            // "orderItem" is entry field
            foreach ( $entry->orderItem as $product ) {
                $products = [
                    'title' => $product->titleVariation,
                ];
            }
            return $products;
        },
    ];
},


Triggering JavaScript from back-end event I'm building a plugin and want to trigger some JavaScript on an event being fired (eg an entry being saved). What is the best way to achieve this? Coming up short looking through the documentation and Stack Overflow.

When an entry is saved, an Entry saved. flash message is set and displayed by Craft. You could use the Control Panel JS plugin to write a script to detect this flash message and perform your desired action.

The flash message is set in a div with an id="notifications". When there is no notification present, this div is empty. When there is a notification present, the div contains another div like this:

Entry saved.

If you test for the presence of this inner div and also the specific notification content (i.e. Entry saved.) you should be able to trigger the actions you need to.


Cannot connect to database with credentials provided in db.php I'm trying to push a site live today and am running into a problem I'm having trouble solving. I have a staging site which is a subdomain on the live server and everything works fine there but when I try to load the live site I get the following error (strange characters and all):

  An exception has been thrown during the rendering of a template ("Craft can't connect to the database with the credentials in craft/config/db.php.") in "_includes/_main_nav" at line 19.

The only difference between the two config files is the database name in db.php and the siteUrl and fileSystemPath in general.php. I do have a multi-environment config based on the one at straughtupcraft.com but I don't see any other difference between my live and staging environments other then what is already noted above.

Anyone run across this problem yet? Solutions?

UPDATE:

index.php:

<?php

//die('hey');

// Path to your craft/ folder
$craftPath = '../craft';

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

if (!is_file($path))
{
    exit('Could not find your craft/ folder. Please ensure that $craftPath is set correctly in '.__FILE__);
}

require_once $path;

// Check the SERVER_NAME variable ourselves
switch ($_SERVER['SERVER_NAME'])
{
    // If the SERVER_NAME variable matches our case,
    // assign the CRAFT_ENVIRONMENT variable a keyword
    // that identifies this environment that we can
    // use in our multi-environment config

    case 'site.com' :
        define('CRAFT_ENVIRONMENT', 'live');
        break;

    case 'staging.site.com' :
        define('CRAFT_ENVIRONMENT', 'staging');
        break;

    default :
        define('CRAFT_ENVIRONMENT', 'dev');
        break;
}

general.php

return array(
    '*' => array(
        'cpTrigger' => 'site_admin',
        'omitScriptNameInUrls' => true,
        'slugWordSeparator' => "_",
    ),
    'live' => array(
        'environmentVariables' => array(
            'siteUrl' => 'http://site.com',
            'fileSystemPath' => '/path/to/domains/site.com/html'
        )
    ),
    'staging' => array(
        'devMode' => true,
        'environmentVariables' => array(
            'siteUrl' => 'http://staging.site.com',
            'fileSystemPath' => '/path/to/domains/staging.site.com/html'
        )
    ),
    'dev' => array(
        'devMode' => true,
        'environmentVariables' => array(
            'siteUrl' => 'http://site.dev',
            'fileSystemPath' => '/users/stubear/sites/site/dev/html'
        )
    ),
);

db.php

return array(
    '*' => array(
        'tablePrefix' => 'craft',
    ),
    'live' => array(
        'server' => 'server',
        'user' => 'username',
        'password' => '********',
        'database' => 'craft_live_db',
    ),
    'staging' => array(
        'server' => 'server',
        'user' => 'username',
        'password' => '********',
        'database' => 'craft_staging_db',
    ),
    'dev' => array(
        'server' => 'localhost',
        'user' => 'root',
        'password' => 'root',
        'database' => 'site-dev',
    ),
);

Move the check the SERVER_NAME switch up above the require_once $path;. You need to set CRAFT_ENVIRONMENT earlier.


Blog Comments / EntryModel.owner is undefined I have build a Blog. Now I've tried to add the commenting function with "Comments":
https://github.com/engram-design/Comments

I use the absolute basic template:
https://github.com/engram-design/Comments/blob/master/examples/standard/standard.html

The call in my Tpl:

{% set params = {
   order: 'dateCreated asc'
} %}

{{ craft.comments.form(entry.id) }}

Until here everything is fine. When I want so send the comment, i always get this Error:

Property "Craft \ EntryModel.owner is undefined.

The "Comments" Plugin use EntryModel.owner when I want so submit a comment on any entry. Now the problem is that {{ entry.owner }} is undefined. But how can I define the {{ entry.owner }}?

I know this is a noobie Question, but how can I fix this?

Somewhere in your template you are trying to access the owner attribute on an EntryModel. The example above doesn't show any details on where you might be trying to do that in your templates.

Try commenting out any area of your template where you may be trying to output values that relate to the Entry Model. Maybe even comment out your whole template. Comment things out until you get your page to load again. As you mentioned this error occurs when you try to send a comment, you may also want to comment things out on whatever template gets loaded after you submit the comments.

Once you're getting the page to load without errors, add your code back line by line until you get the error. This will help you isolate where the error is.

When you find it, you'll probably need to add a conditional check to the offending code to get things working:

{% if entry['owner'] is defined %}
    Then it's safe to try to output {{ entry.owner }}
{% endif %}


Reverse the seomatic title and site name for a specific template Let's say my seomatic Site SEO Name = My Site and my Site SEO Title = A Wonderful Website

With the default values for seomatic's Site SEO Name Placement and Site SEO Name Separator, this will output the following title:

<title>A Wonderful Website | My Site</title>

This makes sense for the majority of pages on my site, where by setting a custom title for the page I'll get something like About Us | My Site

But on the homepage, I actually want to swap the order of these, so that the title becomes:

<title>My Site | A Wonderful Website</title>

This seems like a fairly common thing to do, but I can't seem to find a way to trick seomatic into allowing this without setting Site SEO Name Placement to None (which I don't want to do because the default value works well on all other pages).

Even trying to manually set the entire title won't work, because it will insist on adding the Site SEO Name to the end:

{% set seomaticMeta = seomaticMeta | merge({ seoTitle: 'My Site | A Wonderful Website' }) %}

Any way around this?

The following works (but is undocumented):

{% set seomaticSiteMeta = seomaticSiteMeta | merge({'siteSeoTitlePlacement': 'before'}) %}


Case sensitive Channel urls problem So I have a few different channels for different types of content.

One called pages which is just for regular web pages. All of those entries work uppercase or lowercase so example.com/About and example.com/about both work.

The Entry URL Format for pages is

{slug}

The Entry Template is

/_page

I have a problem with a few of my channels for blog entries and I believe it is because of the Entry URL Format being used, but at the same time that doesn't make sense since it works fine for the page channel. Example channel is called Articles and the Entry URL Format is

articles/{postDate.year}/{slug}

And the Entry Template is

articles/_entry

The main Articles page which shows the index of all articles etc is using

articles/index.html

in the articles directory which is probably causing the problem.

So the problem ends up being that example.com/articles works but example.com/Articles does not and goes to a 404. Now if I am inside of a single entry it can have caps so example.com/Articles/this-is-an-Article works.

This is hosted on a linux server. Only reason I mention that is because how linux handles cases differently, on the staging server which is windows they all work fine. So not sure if I would need to setup 301's for those blog channels using the index.html files inside each channel folder. Or if there is another way of handling this. Possibly a route, or a single but I don't see why that would be needed.

I have some singles setup like this as well but they work with or without caps... so something seems odd about these channels.

Anyone have any thoughts on that.

It's not just Windows / Linux / OSX that have different file system case sensitivities, but even different distributions of Linux can have them.  Or the same distribution, but with different file systems.  Or the same distribution and same file system, but one has been configured to be case sensitive and the case insensitive.

Instead of accounting for all of the different possibilities for a given route (example.com/articles, example.com/Articles, example.com/aRticles, example.com/ArTiClEs), it's going to be much less of a headache to just force lowercase at the web server level.


Save an entry with tags I have a project that the user choose a tag (tags are already created) and save the information.

I try save a entry which has a tag field, all the stuff saves, but the tags don't.  I try search information about that, but any where have a solution or the solution doesn't work.

I try entry form.

Hard to know without seeing some template code, but the syntax for saving existing tags on a front-end entry form looks like this:

<select multiple name="fields[fieldHandle][]">
    <option value="13">Tag Name One</option>
    <option value="42">Tag Name Two</option>
    <option value="144">Tag Name Three</option>
</select>

Replace fieldHandle with the actual handle of your Tags field and 13, 42 and 144 with the actual Tag IDs.

There's a great list of examples for what front-end inputs need to look like for Craft fields here you might find useful: https://straightupcraft.com/articles/craft-cms-field-guide-twig?view=input


Install MySQL stored procedure to database on plugin install in Craft 3 I am trying to add a MySQL stored procedure to the database on plugin install in Craft 3.  I currently have an install migration calling a function from the safeUp method. In this function I am using Craft::$app->getDb()->createCommand(" DELIMITER $$ CREATE PROCEDURE ...")->execute(). However this does not seem to do the trick.

After further investigation Yii handles the DELIMITER ;; in the createCommand() method. I just had to remove the opening and closing DELIMITER syntax and execute the Craft::$app->getDb()->createCommand("CREATE PROCEDURE ( ... )")->execute() for it to install.


Way to getNext() within the same category I'm trying to get the next and previous entries in a structure but I only want the next or previous ones within the same category?

Is it possible to do something like this?

{% set next = entry.getNext().relatedTo(category).first() %}

You're close! getNext and getPrev take an ElementCriteriaModel as a parameter:

{% set params = craft.entries.section('news').relatedTo(category) %}

{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}

{% if prevEntry %}Previous{% endif %}
{% if nextEntry %}Next{% endif %}

Or, if you prefer, a params array (same as you would pass to craft.entries ElementCriteriaModel):

{% set params = {
    section: 'news',
    relatedTo: category,
} %}


Overwrite entry.title in template Does anybody know if it is possible to overwrite entry.title in a template?

The following 2 options causes errors:

{% set entry.title = 'value' %}
{% set entry['title'] = 'value' %}

It's my understanding that Twig's set tag can only be used on variables.

But in your case entry is an object and title is it's property.

You could however create a work-around:

{% set my_title = 'New' %}
{{ my_title is defined ? my_title : entry.title }}

If my_title is defined it will be outputted.


Does Craft commerce support multiple delivery addresses / shipments on same order? we have an ecommerce customer in the gifts market who currently have a custom built ecommerce website. Their USP is that you can order gifts for all your friends and family at once and they will be sent to different addresses on the right days throughout the year.

We are looking at moving them to Craft Commerce. Does anyone know if Craft supports multiple shipment addresses on the same order or any way this could work?

Thank you!

Commerce does not currently support this out of the box (March 2016) - but (just spitballing here, you'll have to try it all out for yourself of course) - you can add arbitrary custom fields to orders.

So you could rig something up by using e.g. a matrix of address field types like this one - https://github.com/elivz/VzAddress-Craft - to store the delivery addresses.  But I am guessing you'd want the address data per line Item, so you could instead perhaps use the line items options system described at the bottom here:
https://craftcommerce.com/docs/add-to-cart

...to add data for the address to each lineitem.

The order itself would have the purchaser's main address associated with it, but you could definitely store addresses either as options with lineitems, or in custom fields on the order, so it would be possible with some effort I'd say.

Also, you'd need to write a custom shipping solution or adjuster plugin that was capable of using the address data stored to calculate the shipping for each of the 'sub orders' and return the total, I suppose.

It's not going to be super simple but Commerce is very flexible and easy to work with when it comes to plugins etc.


How can i apply "current" class for category nav? I've browsed the questions and answers here and i can't find anything that works for what i'm trying to do!

I am using this as the main menu of my site (so it is in _layout.html)

{% nav category in craft.categories.group('artCats') %}
{% set entryCount = craft.entries.relatedTo(category).total()

{{ category.title }}{% if category.level == 2 %}({{ entryCount }}){% endif %}
  {% ifchildren %}

      {% children %}

  {% endifchildren %}

{% endnav %}

It's a drop down menu that shows how many posts are in each sub category. All works nicely!

However, no matter what i try, i can't seem to dynamically assign a class to the current page. I think i'm misunderstanding in general how this is done in Craft.

I see a lot of solutions that are basically saying "if url segment is "fishcake" then add my class" but to me, that's not dynamic at all! Dynamic would be if i add a new sub-category, the menu will add my desired class to that menu item if i visit, without me having to add a new if statement in the Twig code.

Am i able to do something like "if the category.url of this link matches the current url, do this" ?

You can get the current Category Model via the pre-populated category variable on all of your category pages. (→ see Routing type no. 4)

As you probably know, entry pages come with entry pre-populated. To get all the Category Models that are related to an entry page with a Categories Field make a craft.categories call using relatedTo(entry) as a parameter.

Save the Category Model / -Models to a var outside your nav loop, so you don't have to make those requests multiple times. And make sure to save the one Category Model on category pages as an array [myCategoryModel], so you always end up with your variable being of the same type.

Within you nav loop you can now check, if the Category Model of your current loop iteration is within your saved array using the in containment operator.

{# Is this an entry page with a category field? #}
{% if entry is defined %}
    {% set currentCategoryIds = craft.categories.relatedTo(entry).ids() %}
{# Is this a category page? #}
{% elseif category is defined %}
    {% set currentCategoryIds = [category.id] %}
{# None of both? Set an empty array. #}
{% else %}
    {% set currentCategoryIds = [] %}
{% endif %}

{% nav cat in craft.categories.group('artCats') %}

    {% set class = cat.id in currentCategoryIds ? 'current' : '' %}
    {% set entryCount = craft.entries.relatedTo(cat).total() %}

{{ cat.title }} ({{ entryCount }})

{% endnav %}


Has anyone tried a port from Expression Engine to Craft using Verbb's Feed Me plugin? I'm in the process of scoping out a project in Craft, which requires porting an existing site built in EE. The EE site in question relies quite heavily on relationships (using Playa) and not I'm 100% sure how/if Feed Me will be able to retain those relationships when importing into Craft.

Is this possible? Or will we have to remap the relationships after importing the content?

If you import the related items first then you should be able to make the relationship when you import the parent entries.

However, it's really down to the complexity of the relationships.

You may find it simpler to do the import in stages. Start with the bare bones to create entries with the appropriate names/slugs and then bring in the other data bit by bit.

I would favour using XML or JSON for my import format.

I also find it useful to also include some craft fields into which I import the legacy EE id (and any other pertinent information).


Cannot declare class because the name is already in use I'm trying to port a Craft 2 plugin to Craft 3, and don't seem smart enough to work out the namespaces. I've stripped out everything except what the docs recommend, but keep getting Cannot declare class kr37\Calendar37\Calendar37, because the name is already in use  Thank you in advance for any suggestions.

Folder structure

composer.json
src/Plugin.php

Plugin.php

namespace kr37\Calendar37;

class Calendar37 extends \craft\base\Plugin
{
    public function init()
    {
        parent::init();

        // Custom initialization code goes here...
    }
}

composer.json

{
  "name": "kr37/calendar37",
  "description": "Event calendar with unrestricted repetition",
  "version": "3.0.18046",
  "type": "craft-plugin",
  "minimum-stability": "dev",
  "require": {
    "craftcms/cms": "^3.0.1"
  },
  "autoload": {
    "psr-4": {
      "kr37\\calendar\\": "src/"
    }
  },
  "support": {
    "email": "???"
  },
  "extra": {
    "handle": "calendar37",
    "name": "Calendar",
    "developer": "???",
    "developerUrl": "???",
    "hasSettings": "true",
    "hasCpSection": "true"
  }
}

At this point, after much playing around it seems to be working (at least on to the next bit of debugging).

To sum up, it was mostly changes to composer.json, followed by

composer remove kr37/calendar37
composer require kr37/calendar37

src/Plugin.php became src/Calendar37.php
Added "class": "kr37\\calendar37\\Calendar37" to the "extra" part of composer.json
Corrected the autoload "psr-4" to "kr37\\calendar37\\": "src/"
Made sure that all the names matched up just right.
This error, "because the name is already in use," should really be "because the name doesn't match up."


How can you allow users to create products in Craft Commerce I want site members to login and create products in Craft Commerce, so the products they create should only be visible to them on the back-end, e.g,  user (A) should login and view his products in Craft Commerce, user (B) logs in and only see his products.  How can I achieve this in Craft Commerce?

User/User Group permissions don't apply to Product Types in Commerce like they do to Sections in Craft, so I'm not seeing any easy way to pull this off in the Control Panel.

There is a feature request here you might want to comment on if you think this should be the case: https://github.com/craftcms/commerce/issues/174

You could do this from a front-end template/product admin section if you wanted, but not sure if that would be a valid use-case for you.


"Eager loading" of relations like Yii's "with" function Is there any way to "eagerly load" Craft element relations a la Yii's ActiveRelation "with" function?

http://www.yiiframework.com/doc/api/1.1/CActiveRecord#with-detail

This seems like a very handy way to request one big query instead of many small ones in cases where you know up front that you are going to be using all the relations.

** UPDATE **

Okay after experimenting with this, I guess my real question should have been, is there any way to do this kind of thing at the ElementCriteriaModel level, taking advantage of Craft relational fields.

For instance, I want to get a list of children of a Structure entry, along with all the assets in a field:

foreach ($entry->children->find() as $child) {
    // do something with $child->assetsField...
}

Is there any way to load those assets in one big query rather than individually for each child?

This feature has now made it into Craft core as of version 2.6.

See this link for documentation on the subject:
https://craftcms.com/docs/templating/eager-loading-elements


Simple AJAX search form So I've been following the docs on how to create a search form in Craft and it works fine. But instead of having a results.twig page I would like to have just one index page and get all the results with AJAX. Is there a simple way to accomplish this in Craft? And if so, does anyone have an example?

You can create your own search...
lets say this is your html

<input type="input" id="searchTags" placeholder="Search">
<input type="button" id="startSearch" value="Go">

then you have the following script:

$("#startSearch").click(function(){
    var data = {
        action: 'pluginhandle/controller/searchEntries',
        options: $("#searchTags").val()
    };
    $.ajax({
       type: "post",
       url: '/',
       data: data,
       success: function(response){
       // replace content from $("#results") with your new html
       },
    ....
   });
});

Your controller would look like

public function actionSearchEntry(){
     $criteria = new ElementCriteriaModel(ElementType::Entry);
     // build your criteriaModel based on your needs
     $html = $this->renderTemplate('results.twig', array(
         'entries' => $criteria->find()
     ));
     return $this->returnJson($html);
}

your results.twig would be like

{% if entries is defined and entries|length %}

        {% for entry in entries %}

                {{ entry.title }}

        {% endfor %}

{% endif %}


Is there a way to credit a customer's account in Craft Commerce? Our client would like to accept gift certificates as a form of payment. I've looked into the 2 stripe plugins they offer for gift certs, but neither of them will work for my client -- one is a separate off-site gateway, and the other is $90 a month, which is off the table completely.

Is there a way to assign credit to a user's account and allow them to take that amount off before the purchase? So we would sell the gift certificate and enable it on the user account, then they could purchase things online?

Any other good ideas on how to handle gift certs?

Commerce does not, currently (= Dec 16) have any concept of a customer balance or a gift certificate.

You could do it as a plugin, I would think.  Basically you'd keep a list of emails and credits in a record (i.e. table) and then write a controller that you/the customer could call to apply those credits - the actual application of which you'd probably implement as a Commerce adjuster perhaps (https://craftcommerce.com/docs/adjusters).

It would be a relatively involved plugin at this point.

In our case we chickened out on this, hoping it will come later to Commerce core - we just ask that the gift certificate customers call through their order.  Definitely not ideal but for the relatively few GC customers it didn't seem worth the development effort.   Gift certificates are an often requested feature for Commerce, though, so you'd expect it to happen at some point.

Vote here for the feature - https://github.com/craftcms/commerce/issues/253


Recommended hosting company for a Craft site? Looking through the Google Plus community and Slack chat history, there have been many suggestions regarding hosting for Craft websites. It may not be possible to get a single conclusive answer, but I still want to know...

What hosting company do you recommend for a Craft website?

TL;DR

DigitalOcean (droplet running Ubuntu 14.04)
ServerPilot
Email hosted elsewhere

Personally, I've had great experience with DigitalOcean.
It is a VPS solution with virtually nothing pre-installed. I've found it to be amazingly fast and stable, even for sites with a high volume of traffic. Spinning up a new VPS "droplet" is incredibly simple and painless.
Since it's basically an "empty" server when you create a new droplet, I've found that DigitalOcean pairs well with ServerPilot. Keep in mind that ServerPilot requires your droplet to be created with Ubuntu 14.04, and must run its setup before you do anything else with your droplet.
ServerPilot gives you an easy interface to setup the common software you'll need to run your site... namely PHP & MySQL. Using both services combined, we're able to easily spin up a new droplet, set it up with ServerPilot, and be up and running quickly!
Only downside... email hosting is not included in either service. So you'd need to find a separate service to handle email hosting. (We use Zoho, which I find to be adequate. I'm still on the lookout for the "perfect" email solution, but that's a topic for another day.)


Craft 3 Redirect after login based on User field i'd like to alter the after login redirect URL based on a User custom field, i encountered this but looks like it's not applicable to Craft 3.

I could re-write the whole UsersController class on a custom plugin but maybe there's another way?

I believe you could use Freeform's Element Connections to create a user registration form. In the form's Return URL setting it looks like there's some options to create some logic with {{ submission.id }}.


What do I use for the Path to the Craft folder? I want to place my Craft folder above the root.   But, this is for an add-on site that sits within the public_html folder of the main site.

So, the index.php file sits here...

../public_html/add-onsite-folder/public/index.php

The Craft folder sits just above the /public_html folder of the main site.

So, how - specifically - do I set the $craftPath?   It's not the default '../craft'; and I have tried numerous variations.

I am not installing locally.

Thanks

You will definitely want to put it above the root even if it's an add-on site, in which case the proper setup would be '../../../../craft' but this would generate a conflict with the main site craft install since there would be two folders with the same name above /public_html, so you could rename the add-on site craft folder to craftaddon and than the path would be '../../../../craftaddon'.

In case there's a really good reason for leaving it below the root, you would just use '../../../craft' but that does come with security risks that are pretty much not worth taking.


Craft sometimes takes several minutes to respond to a request I have a pretty simple Craft site running a Digital Ocean Ubuntu droplet and for some reason it can sometimes take several minutes to save an entry.

I think this might be something to do with sessions as, when it happens, the site stops responding completely for that browser unless I quit and re-open it. Whilst it is happening, accessing the website via another browser works fine. There's nothing in the phperrors.log or the craft.log that even relate to the time the problem happens but there's something in the Application Logs that seem relevant.

Here's a sample of the 'Profiling Summary Report' where you can see it took 300s to respond but none of the queries takes anything other than milliseconds: http://pastebin.com/pbf7bj2e

The interesting bit is is the Application Log where you can see the timestamps jump from 13:00 to 13:05 on line 58:

http://pastebin.com/gdCgTUSC

What is happening there that took 5 minutes?

I have had this same experience many times, but only with certain hosting providers, so I suspect it has something to do with server configuration.  One thing that I noticed was that saving an entry, for example, would hang, but the entry had indeed been saved pretty much immediately.

I know it is not my local setup, because my co worked, who works from a different location, had the same issues at the same time.  Next time it happens I will try accessing via IP.


CP search for entries by postDate? Does the control panel search support postDate, expiryDate, dateCreated, dateUpdated?

For a custom date field, the below will return all dates in October 2017:
customDate:2017-10

But for entry attributes like postDate it returns nothing:
postDate:2017-09

Sure would be good to be able to search by these date values.

Currently, the postDate of an entry is not indexed for search.

Kind of hacky, but you could make a custom DateTime field with duplicate information (i.e. myPostDate) and do a search based on that.


Admin - Manage entries based on a field type choice I have a potential upcoming project which will be the home for a businesses sporting events, they will have multiple event mini sites, about 4 each year. Each event mini-site will have the same structure but they will have different aesthetics.

The content areas will be:

Home (Single)
News (Channel)
Videos (Channel)
Photos (Channel)
Results (Single)
Media Contacts (Single)

I have no problem setting up the site but I would like offer the client the ability to access an edit entries screen that has just the content for that event.

I.e they could choose the Event from an drop down and they would only see the Singles, Channels and Structures related to that event.

Also adding the ability to restrict some users access to a particular events content

Is this possible? Has anyone built a plugin for something like this? or know how to?

Thanks in advance.

It's not (yet) possible to have multiple websites with dedicated front-end and back-end views within one Craft installation (Multi-site feature). There's some users that mis-use Craft's localization feature for this, but I definitely wouldn't recommend this.

But it is actually not a problem at all to route all your subdomains to individual template folders of a single installation (→ Is it possible to route a subdomain to specific template group?). And for the backend, I'd simply create a user group for each of your events and configure the permissions accordingly (→ Assign permissions to users and groups). So user group "Summer Party" has only access to sections belonging to that sub-site. Individual users can be assigned to more than one group if necessary.

Instead of having lots of single sections ("Summer Party - Home", "Summer Party - Results", "Summer Party - Media Contacts") I would recommend to look into replacing this with a single structure section ("Summer Party - Pages") with multiple entry types. And for your media channels you could also consider not using entries at all and assign fields to your assets directly.


Clarification on Feed Me > Feed URL The Feed Me documentation says

  "Provide the URL for your feed. This can be an absolute URL, relative (to the web root) and make use of any aliases"

That's pretty confusing language. I thought I could create a folder in public called "feeds" that would contain my .csv. For example, /public/feeds/feed.csv. So I entered feeds/feed.csv in the Feed URL field. That didn't work. I was confused because "relative (to the web root)" doesn't really mean a relative path.

Is it true that the Feed URL needs to be an absolute URL in the form of http(s)://domain.tld/feed/feed.csv? I understand that aliases can be used and you wouldn't necessarily need to enter the domain in this field, but in general is this the required format?

i placed  a test file named test.json in web folder of Craft CMS and put test.json in feed URL and it doesn't work -so it is not relative to web root as default-.

but when it says absolute format i believe it is  /var/www/html/craft/web/test.json -in local ubuntu, in your case maybe {maybe top folders}/public/feeds/feed.csv- or as path alias format: @webroot/test.json which both of them works for me.

as you mentioned URL format http(s)://domain.tld/test.json or @web/test.json works too.

docs for path alias


Is it possible to cache variables using the {% cache %} tag? I would like to cache a variable and compare the cached variable with a parameter from the query string.

Is it possible to somehow cache a variable ?

{% cache using key "cacheId" %}
  {% set id = 1 %}
{% endcache %}

You can accomplish this by using the set/endset tags to create a variable from the cached output:

{% set finalVariable %}
    {% cache %}
        {# heavy lifting (like queries) here #}
        {# output the contents of your variable here #}
        your output here or {{ yourOutputHere }}
    {% endcache %}
{% endset %}

In the above example the finalVariable will be set to the value of the cached content.

Or, in the case of the code example used in the question, something like this could be used:

{% set id %}{% spaceless %}
    {% cache using key "cacheId" %}
        1
    {% endcache %}
{% endspaceless %}{% endset %}

It's a very basic example that would probably never be used, but the id variable would be set to a string of 1 from the cacheId cache.

Note: The spaceless tags are just used to remove the whitespace.


Searching members fields I'm building a Users search page.

I want to search the members group based on the following fields that I've setup for Users:

First Name
Last Name
Company Name (handle: genericCompany, type: Plain Text)
Company Overview (handle: membersCompanyOverview, type: Rich Text)
Contact (handle: membersContact, type: Plain Text)
Contact Email Address (handle: globalEmailAddress, type: Email Address)
Contact Position (handle: genericPosition, type: Plain Text)
Services (handle: membersServices, type: Categories)
Locations (handle: membersLocations, type: Categories)

My HTML form (removed labels etc to keep form example clean):

<form id="directory_search_form">
    <input type="text" name="keywords" value="">
    <input type="checkbox" name="services[]" value="service-1">
    <input type="checkbox" name="services[]" value="service-2">
    <input type="checkbox" name="services[]" value="service-3">
    <input type="checkbox" name="locations[]" value="location-1">
    <input type="checkbox" name="locations[]" value="location-2">
    <button type="submit">Go</button>
</form>

My jQuery:

var form = $("#directory_search_form");

form.on("submit",function(event) {
    event.preventDefault();

    var errors = 0;

    if(!$("#keywords").val()) {
        errors++;
    }

    if(errors == 0) {
        $.post("/search",$(this).serialize()).done(function(result) {
            $("#results").html(result);
        });
    } else {
        alert("Please enter some keywords and try again.");

        return false;
    }
});

My Search template:

{% if craft.request.isAjax %}
    {% set params = craft.request.getPost() %}
    {% set keywords = "" %}
    {% set serviceCategories = craft.categories.group("services") %}
    {% set locationCategories = craft.categories.group("locations") %}
    {% for key in params | keys %}
        {% if key == "keywords" %}
            {% set keywords = params["keywords"] %}
            {% set keywords = keywords | trim %}
        {% endif %}
        {% if key == "services" %}
            {% set services = params["services"] %}
            {% set servicesCategories = services | join(", ") | trim %}
            {% set serviceCategories = craft.categories.group("services").slug(servicesCategories) %}
        {% endif %}
        {% if key == "locations" %}
            {% set locations = params["locations"] %}
            {% set locationsCategories = locations | join(", ") | trim %}
            {% set locationCategories = craft.categories.group("locations").slug(locationsCategories) %}
        {% endif %}
    {% endfor %}
    {% set members = craft.users.group("members").status("live").relatedTo([ "and", { targetElement: serviceCategories }, { targetElement: locationCategories } ]) %}
    {% if members | length %}
        {% for member in members %}
            {{ member.email }}<br>
        {% endfor %}
    {% endif %}
{% endif %}

This gives me all members for selected categories.  However I want to hook up the keywords field to further search users.

I also want to get only those users that are related in all categories not either categories.

I've got the keywords but if I add

.search("*" ~ keywords ~ "*")

I don't get any members for my keywords - e.g Operations Manager when there are Members in the system with Contact Position field set to Operations Manager.

I want to search by multiple keywords and multiple categories.

What am I doing wrong?

Please see Users relatedTo multiple categories for improved answer since this questions details are outdated.


Errors with Craft 2.3, Imagine and Imagick Does anyone else have the same issue?

Post the recent Craft 2.3 update all image transforms on my server (about 6 craft sites now) are throwing errors on new transforms.

Specifically write errors from the Imagine library's Imagick classes.

My directories are writable and these sites have been working for some time. No new updates on the server, standard Debian lamp stack.

I've tracked it down / fixed it by explictly selecting my 'imageDriver' in the config. The docs say this is a new setting in 2.3.

It seems the default of 'null' is calling 'imagick' but not working, whereas choosing 'imagick' in the config makes it work?


Database Exception with Sprout Forms after updating to Craft 3 I've recently updated a site from Craft 2 to 3. I'm getting this error after login in to the admin regarding Sprout Forms which was installed in my Craft 2 install.
What can I do to get the back-end functioning again? The front-end is fine apart from the pages which contained sprout forms, which I've removed.

Error Info: Array
(
    [0] => 42S22
    [1] => 1054
    [2] => Unknown column 'sproutforms_forms.saveData' in 'field list'
)
↵
Caused by: PDOException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sproutforms_forms.saveData' in 'field list'
in (path)/vendor/yiisoft/yii2/db/Command.php at line 1258

This issue is often caused if you don't first update Sprout Forms to v2.5.1 before the upgrade to Craft 3.

If something goes wrong with a plugin installation you can usually disable or remove it in the plugins table in the db. To disable it you can set the column plugins.enabled to 0 in the row for the plugin you wish to disable.

Going a step farther you can delete the plugin's row from the plugins table and remove any related tables in the database that relate to that plugin. Be sure to backup your database before editing it directly.

After that, be sure to reach out to support for the respective developer and let them know what steps they can take to recreate the problem. You can contact Sprout support at: sprout@barrelstrengthdesign.com


Importing/Exporting, but not everything I have a dev server and a production server, they are on two different databases. The editors will only be logging into the production space to add content. I'm looking for an easy (but still manual) way to export content. I rather not do an entire database dump every time.

Any thoughts?

You don't wish to just pull down the production environment to your development server? This is how we solve this problem at work, by only editing the production server's database and then pulling it when it is updated.

There are quality scripts for syncing environments from the command line. You can simply run ./pull_db.sh and it will do everything for you.
https://github.com/nystudio107/craft-scripts

There are also new craft 3 plugins for export/import but I have not had much success so far.


Display images in Matrix block in grid view I have images in matrix block
I want to display in grid format
Each raw will have three column.

Images 1   images 2  image2
Images 4  images4  image 4

I tried to used batch filter but did not work with matrix block.

 {% for block in entry.profilematrix %}
{% switch block.type %}

{% case "profilebuilder" %}

{% set debfilter = block.department %}

        {# use the variable to filter the entries #}

        {% if block.department == craft.request.lastSegment   %}

                 {% for image in block.uploadImageProfile %}

             {% endfor %}

        {% endif %}

 {% endfor %}

  {% endfor %}

{% for batch in block.images|batch(3) %}

  {% for image in batch %}

  {% endfor %}

{% endfor %}


Get the Category name into the URL for an entry I have a gallery which is categorised. The gallery is a Structure section where the user adds an entry and then assigns it to a category - all good.

At the moment, when clicking on an entry title the URL is mysite.com/gallery/entry-slug  but I would like it to be mysite.com/gallery/category-name/entry-slug.

I've looked around the Docs and StackExchange for a simple answer (assuming it would just be the addition of a tag) but the solutions seem very convoluted and way outside my grasp of understanding.

Any help appreciated

Thanks

A Categories field can be related to several categories. So you'll either need to limit your Category field to a single Category relationship or you'll need to make some assumption in how you build your URL as to which category will appear in the URL. The simplest assumption to make will be that you will always return the first category for your URL.

Entry URL Format in the Section Settings:

gallery/{categories.one().slug}/{slug}

Entry Page URL:

http://mysite.com/gallery/category-slug/entry-slug

In the Entry URL Format setting above, you are telling your slug to return the slug of the first item in your array of categories using this line: {categories.first().slug} where categories is the handle of your Categories Relations field.

You may also want to ensure your Categories Relations field is required.


Only Install migration is applying on plugin install I have a custom plugin which is added via path repository on local.
I have some migrations in the src folder.

My problem is if I uninstall the plugin and install it again, I can see all of the migrations in the migration table, but only Install migration is applied.

If I change the version and schema version of the plugin and remove and require the plugin again, I get update plugin notification on the dashboard and all of the migrations are applied correctly.

also if i create and apply these migrations via command i can see change in databases.

i don't why migrations aren't applied on plugin install -except Install migration-?

It sounds like it's working as expected.

When you add a new migration for your plugin, you're expected to update your plugin's Install.php migration with the new schema changes as well.

You can see the relevant code here: https://github.com/craftcms/cms/blob/develop/src/base/Plugin.php#L149-L161


Assets problem (/cpresources/transforms/) after update to Craft Client 2.5.2750 Hi I've just updated to Craft 2.5 but ran into a problem. All my assets are now broken (also showen broken assets icons). I've cleared my cache, went to my craft_tasks table and adjusted the running task there but still it won't show me my assets again...

Any suggestions someone?

I had similar issue but I was tinkering with Elements API. The JSON payload gave me that cpresources/transforms/ but once I clicked on the link it shows the proper image with the transforms applied.

Upon returning to the JSON printout, the URL for the assets looks correct. In my case it is pointing to the S3 bucket I had setup previously.


Global field duplicated I have two sites. Everytime I add global field content (slogan for example) it adds the same to the second site, and vice-versa. Anyone has any idea how to stop that?

In order to change the content for each site individually you need to set the field settings accordingly to "translatable for each site"

Otherwise the content for each site will be the same


Changing a product's Tax Category ID onSaveProduct event I'm trying to alter a products tax category whenever it's saved based on a condition.

craft()->on('commerce_products.onSaveProduct', function(Event $event){
    $product = $event->params['product'];
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->id = $product->productFilterArtist[0]->id;
    $artist = $criteria->first();

    //Craft::dd($product->taxCategoryId); // 2

    if ($artist->getContent()->vatRegistered) {
        $product->taxCategoryId = 1;
        //Craft::dd($product->taxCategoryId); // 1
    }

    $success = craft()->elements->saveElement($product);

    //Craft::dd($product->taxCategoryId); // 1
});

It appears to work as the output of each Craft::dd is correct. However the entry still shows the original tax category in the CP.

I have been able to alter the shipping category in the same way without trouble. Am I missing something?

Setting the new field value onSaveProduct meant that the only the general element and its custom field data was being saved and not the tax ID on the product model.

To solve this, the onBeforeSaveProduct event should be used. This allows modification of the product model before it's saved.

craft()->on('commerce_products.onBeforeSaveProduct', function(Event $event){
    $product = $event->params['product'];
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->id = $product->productFilterArtist[0]->id;
    $artist = $criteria->first();
    if ($artist && $artist->getContent()->vatRegistered) {
        $product->taxCategoryId = 1;
    }
})


Order entries by content of their fields Can I order entries by the content of a field every entry has?

{% for entry in craft.entries.section('entries').order(  *first time field of a matrix block within the entry*  ).all() %}

You need to join the Matrix table and the Matrix content table in that case to order by this specific field. LeftJoin will allow you to only join the first block. If you have several different block ids you need to leftJoin only blocks with your block type ID

{% set field = craft.app.getFields().getFieldByHandle('yourFieldHandle') %}
{% set entries = craft
    .entries()
    .section('entries')
    .leftJoin('{{%matrixblocks}} matrixblocks', '[[matrixblocks.ownerId]] = [[elements.id]]')
    .leftJoin(
        field.contentTable . ' myContentTable',
        '[[myContentTable.elementId]] = [[matrixblocks.id]]'
     )
    .orderBy({'myContentTable.fieldprefix_fieldHandle': SORT_ASC})
    .all()
%}

change myContentTable.fieldprefix_fieldHandle to your exact DB column or fetch it dynamically.


Craft 2 CP session expires unexpectedly, requires repeated login Environment
Craft: 2.6.3013 (Personal)
MAMP Pro: 4.4.1
PHP: 7.0.12 (CGI Mode)

Behavior
After logging into the CP, and following a relatively short period of time, the session expires unexpectedly and Craft requests a login. Attempting to log in fails and immediately returns to the login modal; however, simply refreshing the page re-establishes the session, but again for only the limited period of time.

Looking at /craft/storage/runtime/sessions I see that Craft is creating a number of sessions, some of them being zero bytes.

Attempted Solutions
I've tried the following, based on other users' past experiences and solutions:

In general.php: 'requireMatchingUserAgentForSession' => false
In general.php: 'overridePhpSessionLocation' => true
In php.ini: session.auto_start = 0
Permissions set to 777 for /craft/storage/runtime
In MAMP, enable/disable "Xdebug (Debugger)" PHP extension
Lastly, tested in both PHP 7.0.12 and 5.6.32 without CGI mode

Next Steps?
Does it appear that I've missed anything in my previous steps? I've been using Craft 2 for a couple of years in a variety of environments--MAMP 3 / Vagrant / Docker--and haven't experienced this before. The issue isn't a showstopper, but certainly an annoyance, and I would be grateful for thoughts on what to try next.

Resolved.

This ended up being an issue with, so far as I can tell, my env variables--specifically a misconfiguration with the basePath.


Dynamic URL generated by a custom field dropdown value I have a special case where the URL needs to be defined from within the entry itself. I have a dropdown that I want to populate with the URLs as values.
Can the dropdown value be used to generate the URL? I can not use custom site URLs because the customer/user needs to see the URL themselves from within the entry.
The entry is a channel.
So let's say the dropdown has a label called "Monkey". Then I want the URL to be /monkey/article-slug.

In the section settings, you can specify a dynamic entry URI format.
As the docs say, this box is in fact a mini Twig template, and is preloaded with the element being saved (accessible as object) and its custom fields (accessible directly by their handles). Good to know that you can also use a shortcut syntax with single braces instead of double ones here.
So in your case you'd want something like:
{slugPrefixFieldHandle ? slugPrefixFieldHandle ~ '/' ~ slug : slug}


PayPal Express not redirecting back to Craft Commerce I have entered API Username, Password and Signature from PayPal and added 'tokenParam' => 'craftToken' in Craft config and yet when I try to make a payment using PayPal Express I get the following....

https://www.site.com/index.php/actions/commerce/payments/completePayment?commerceTransactionId=114&commerceTransactionHash=0ec5451ed35b360311214dfa75aee88f&token=EC-9GX1527947961953D&PayerID=RFN3LXKUP6SVQ

With the following error:  The requested URL was not found on this server.

Any suggestions on what I have missed.

Here is my craft/config/general.php file.

$domain = 'www.site.com';

if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $domain . $_SERVER["REQUEST_URI"]); exit();
}

define('URI_SCHEME',  ( isset($_SERVER['HTTPS'] ) ) ? "https://" : "http://" );
define('SITE_URL',    URI_SCHEME . $_SERVER['SERVER_NAME'] . '/');
define('BASEPATH',    realpath(CRAFT_BASE_PATH . '/../') . '/');

return array(
    '*' => array(
            'siteUrl' => SITE_URL,
            'environmentVariables' => array(
            'siteUrl'  => SITE_URL,
            'basePath' => BASEPATH,
            'defaultImageQuality' => 60,
            'omitScriptNameInUrls' => true,
            'tokenParam' => 't',
        ),
    ),
);

FORM

{% if cart.paymentMethodId %}

    <form method="POST" class="form-horizontal" id="paymentForm">

        <input type="hidden" name="action" value="commerce/payments/pay"/>
        <input type="hidden" name="redirect" value="/shop/customer/order?number={number}"/>
        <input type="hidden" name="cancelUrl" value="/shop/checkout/payment"/>

        {{ getCsrfInput() }}

What's the output in your templates of:

{{ craft.config.tokenParam }}

If it isn't t suspect your config is not setting the tokenParam for some reason.

Can you test with a stripped out general.php with only hard-coded values (No multi-environment config, or if($_SERVER ... checks)

return array(
    'tokenParam' => 'myCraftToken'
    // ..other hard coded settings
);


Get Section Handle From Group I have a landing page on my site where I want to list a group of sections that have entries. I also need to access the section handle of that same group of sections.

I am having problems getting the section handle for the sections.

Currently I get an error back that says impossible to access attribute ("handle") on a string variable.

        {% set specialEntries = craft.entries.section(['sec1','sec2','sec3']) %}

        {% set grouped = specialEntries|group('section') %}
        {% for section, specialEntries in grouped %}
            <h1>{{ section }} - {{ section.handle }}</h1>
        {% endfor %}

In your example, you're attempting to use a SectionModel instance as the key for your grouped entries. This is not possible.

What actually happens behind the scenes is the group filter generates an object where the keys are the string value of the SectionModel instance [1], and the values are the EntryModels associated with that section.

There are a few ways of achieving your desired outcome. Here's one possibility (not tested):

{% set sections = craft.sections.getAllSections() %}
{% set entries = craft.entries.section(['first', 'second', 'third']) %}
{% set grouped = entries|group('section') %}

{% for sectionHandle, sectionEntries in grouped %}
    {% set groupSection = false %}
    {% for section in sections %}
        {% if section.name == sectionHandle %}
            {% set groupSection = section %}
        {% endif %}
    {% endfor %}

    {% if groupSection %}
        <h1>{{ groupSection.name }} - {{ groupSection.handle }}</h1>
    {% endif %}
{% endfor %}

[1]: The SectionModel::__toString method returns the name attribute.


Help Understanding Craft Email Settings I have a client who uses Office 365 for email.  Using the basic phpMail config in Craft fails when I try to direct an email to any of the clients email addresses, including user registration and, more importantly, when sending a message from the Contact Form plugin.

I have tried in vain to change the Craft email settings to SMTP, using credentials that have been tested with a desktop email client.  I am sure there is something I am missing, e.g. some server config thing.

Any advice would be greatly appreciated!

Roi

It could be your server blocks outgoing mail on the default port (25). Try port 587 instead.


How can I get an S3 asset's remote path minus the bucket name from within my plugin? My plugin takes as an argument the id of an asset. So I'm starting from here:

   $entry = craft()->elements->getElementById($entry_id);

Assuming my asset has the url http://mybucket.mycompany.com/uploads/pdfs/myfile.pdf, how can I return just 'uploads/pdfs/myfile.pdf' from within my plugin?

I'd just use the replace filter to chop it off...

  https://craftcms.com/docs/templating/filters#replace

Even if you didn't know the bucket name exactly, replace supports regex.


Prevent Asset Transforms from scaling Image past 100% There is almost never a reason why I would want an image to be scaled past 100% by a transform. This usually results in an image being looking worse than it would if scaled by the browser. Is there a way to tell Craft not to scale an image past 100% of its original size, even if the transform width is larger?

Yes.

getWidth will give you an image's width: {% set originalWidth = image.getWidth(false) %}. You want to apply the transform if desiredWidth is less than originalWidth. I would write a twig macro:

{% macro transform(image, desiredWidth) %}
  {% set originalWidth = image.getWidth(false) %}
  {% if desiredWidth < originalWidth %}
    {{ image.getUrl({mode: 'fit', width: desiredWidth}) }}
  {% else %}
    {{ image.getUrl() }}
  {% endif %}
{% endmacro %}

You could also do the same test, and then conditionally setTransform on the image.

If you define your transforms in the CP the macro would be like this:

{% macro transform(image, transformHandle) %}
  {% set originalWidth = image.getWidth(false) %}
  {% set transformedWidth = image.getWidth(transformHandle) %}
  {% if transformedWidth < originalWidth %}
    {{ image.getUrl(transformHandle) }}
  {% else %}
    {{ image.getUrl() }}
  {% endif %}
{% endmacro %}


Getting database error when calling CateogoryService method I have a PHP file in the public_html titled categories.php with the following code:

namespace Craft;
$craft = require '../craft/app/bootstrap.php';
$categories = $craft->categories->allGroupIds();

Running this script results in the following message:

Error error
Craft can’t connect to the database with the credentials in craft/config/db.php.

My craft/config/db.php file looks like this.

return array(
    '*' => array(
        'tablePrefix' => 'craft',
    ),
    'live' => array(
        'server' => 'localhost',
        'user' => '',
        'password' => '',
        'database' => '',
    ),
    'staging' => array(
        'server' => 'localhost',
        'user' => 'DB_USER',
        'password' => 'DB_PASSWORD',
        'database' => 'DB_NAME',
    ),
    'dev' => array(
        'server' => 'localhost',
        'user' => 'root',
        'password' => 'root',
        'database' => 'DB_NAME',
    ),
);

I'm not having database trouble anywhere else, only when I try to call any CategoriesService methods. Is there something that I'm failing to understand here?

Solution:

The CRAFT_ENVIRONMENT constant was being set in public_html/index.php, so my craft/config/db.php file could not choose the correct database credentials. The issue was resolved by setting the constant to 'dev' in my categories.php file, like below.

namespace Craft;
define('CRAFT_ENVIRONMENT', 'dev');
$craft = require '../craft/app/bootstrap.php';
$categories = $craft->categories->allGroupIds();

You don't show how you're defining the 'live', 'staging' and 'dev' keys for the multi-environment config, but most likely you just need to explicitly set the CRAFT_ENVIRONMENT PHP constant in your categories.php file to tell Craft which database credentials to choose.


Not finding template when adding "tag" view Not trying to do anything fancy here, just trying to have a "tag" view similar to my category view (which uses the same template), however, when I add my link, /blog/{{ tag|slugify}} (I'm using Slugify to generate a slug out of the tag name.), it returns the "Unable to find the template â€œ_layoutâ€" error. This should load the /blog/index.html template but it is not. My category view is working as well as the main load. (I am getting the same error when trying to do an author /blog/{{ entry.author.username }}) What am I missing?

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

If the URI looks like this: blog/*

Load this template: blog/index

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


if/else loop with (almost) daily events Building further on this problem, I try to make a loop that exits when the next opening hours or in other case events are found.

There is an event on all days except monday. I added a couple of extra elseif statements in case they drop a couple of events.

I have the following code (based on the answer below I changed my code)

{% for entry in craft.entries.section('events').level(2) %}
  {% if entry.dayOfEvent == now|date("l") %}
    {{ entry.dayOfEvent }}
  {% elseif entry.dayOfEvent == now|date_modify("+1 day")|date("l") %}
    {{ entry.dayOfEvent }}
  {% elseif entry.dayOfEvent == now|date_modify("+2 days")|date("l") %}
    {{ entry.dayOfEvent }}
  {% elseif entry.dayOfEvent == now|date_modify("+3 days")|date("l") %}
    {{ entry.dayOfEvent }}
  {% else %}
{% endfor %}

But this doesn't seem to do it. It's probably basic stuff, but what am i doing wrong?

Update

Based on the answer below I changed my code

The output clearly gives me my days. But the {% elseif %} doesn't work, I just get the day outputted as well for all events in that range. Shouldn't it exit the loop as soon as the condition is met?

It's probably because entry.dayOfEvent isn't returning exactly what "now"|date_modify('+1 day') is returning therefore the comparison fails.  Maybe one includes the time and the other doesn't, for example.

You can see what each is returning by doing:

{{ entry.dayOfEvent }}
{{ "now"|date_modify('+1 day') }}

If they are different formats, then you can make the 2nd one match the format of the first by using Twig's date format method.


Pushing to an array within a class doesn't work Apologies if this ends up being a silly syntax oversight.

My services file looks like this:

class MyPluginService extends BaseApplicationComponent {
  public $myArray = array('test1', 'test2');

  public function someFunction() {
    $someText = "This should end up in myArray";
    array_push($this->myArray, $someText);
  }
}

Assuming the "someFunction" has been called, I later try to dump the array.

{{ dump(craft.myPlugin.myArray) }}

Expected output:

  array(2) { [0]=> string(5) "test1" 1=> string(5) "test2" [2]=>
  string(29) "This should end up in myArray" }

Actual output:

  array(2) { [0]=> string(5) "test1" 1=> string(5) "test2" }

The solution seems to be pretty unanimous across many PHP related forums. However, this just isn't working in my Craft project. Have I overlooked something obvious, or is Craft protecting the public array in some way?

I feel like we're missing some code in your examples, but in a plugin there is no direct link between a template and its services.  You go through a Variable class, which is responsible for exposing your service's methods.

So in your example, in your plugin's variables folder, you'd have a MyPluginVariable class that has it's own someFunction method like this:

class MyPluginVariable
{
    public function getMyArray()
    {
        return craft()->myPlugin->myArray;
    }

    public function someFunction()
    {
        return craft()->myPlugin->someFunction();
    }
}

Then from your template, assuming you call someFunction() first, you should get the correct output.

{{ craft.myPlugin.someFunction() }}
{{ dump(craft.myPlugin.myArray }}

I'd also recommend refactoring your service to encapsulate the public array in a method and use the PHP [] syntax to avoid the function overhead of array_push().

Something like this:

class MyPluginService extends BaseApplicationComponent
{
    private $_myArray = array('test1', 'test2');

    public function someFunction()
    {
        $someText = "This should end up in myArray";
        $this->_myArray[] = $someText;
    }

    public function getMyArray()
    {
        return $this->_myArray;
    }
}

Then your Variable's getMyArray() method would change to this:

public function getMyArray()
{
    return craft()->myPlugin->getMyArray();
}


How to create new variable from For Loop results I need to get a list of all the "sizes" from my Table type field column. The list of sizes needs to be separated by a "|"... eg: small|medium|large

My Table type field name is "productAttributes" and the column in that field is "size".

How can I string together the results of a For Each loop to create a new variable with Twig?

If I understood your question correctly then you should be able to do it as follows:

{% set sizes = [] %}

{% for productAttribute in entry.productAttributes %}
    {% set sizes = sizes|merge([productAttribute.size]) %}
{% endfor %}

{% set sizes = sizes|join('|') %}

The sizes variable will then be a string containing the pipeline separated sizes, for example:

small|medium|large


Adding items to cart from related entry not working Folks:

I have a list of accessories related to a main product. After adding the main product to the cart, the user can then add accessories related to that product.

The code seems to check out. The price and purchasableId for the related product are coming through just fine. However, when you click the "Add to Cart" button for the related product, the page refreshes but nothing is added to the cart. Relevant code:

{% set cart = craft.commerce.cart %}
{% for relatedProduct in product.relatedAccessories %}

{{ relatedProduct.title }} - {{ relatedProduct.accessoryDescription }} - {% for variant in relatedProduct.variants %}{{ variant.salePrice|currency('CAD', true) }} - {{ variant.purchasableId }}{% endfor %}

 <form method="POST">
    <input type="hidden" name="action" value="commerce/cart/updateCart">
    <input type="hidden" name="redirect" value="commerce/cart">
    <input type="hidden" name="qty" value="1">
    {% for variant in relatedProduct.variants %}<input type="hidden" name="purchasableId" value="{{ variant.purchasableId }}">{% endfor %}
    <input class="btn  btn-d  btn-lg" type="submit" value="Add to cart">
</form>
{% endfor %}
{% endfor %}

The source code for the rendered page looks like this:

Accessory description - $50

<form method="POST">
    <input type="hidden" name="action" value="commerce/cart/updateCart">
    <input type="hidden" name="redirect" value="commerce/cart">
    <input type="hidden" name="qty" value="1">
    <input type="hidden" name="purchasableId" value="65">
    <input class="btn  btn-d  btn-lg" type="submit" value="Add to cart">
</form>

As far as I can see, this should be working. But again, nothing is added to the cart.

Does anyone have any ideas?

Just quickly as I'm on my phone...The two main ways to debug this sort of thing in Commerce are:

Check what you are actually POSTing matches what you think you are posting (to check this I just use the browser dev tools)
Check the flash data (notice and error) for messages when the page reloads (or check the JSON response if ajaxing).

Usually you'll get a sensible message back, e.g. out of stock or similar.

I use this code to dump the flash data (I think only error and notice are used these days, the commerce flash dates back from before commerce was released but it can't hurt!):

{% if craft.config.devMode and (craft.session.hasFlash('commerce') or craft.session.hasFlash('notice') or craft.session.hasFlash('error')) %}

        {% set isErrors = true %}
        {% set commerceFlash = craft.session.getFlash('commerce')|join('|') %}
        {% set noticeFlash = craft.session.getFlash('notice')|join('|') %}
        {% set errorFlash = craft.session.getFlash('error')|join('|') %}

        Commerce: [{{  commerceFlash }}]
        Notice: [{{  noticeFlash }}]
        Error: [{{  errorFlash }}]

    {% endif %}


Two Domains. One Repo. Need Second License I have two different domains that are both being deployed from the same Github repo. Domain A has a Craft license. Domain B needs a Craft license. I don’t want to transfer from Domain A to Domain B but they are both reading from the same craft/config/license.key file.

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


How do I set mime-types for Craft templates? For example, if I'd like to serve a file as application/json or application/rss+xml

I see in the RSS Feed documentation that it mentions saving a file with .rss will auto-detect and serve the correct mime-type.

However, how is this detected? Is there a set list that the CMS uses based on the extension or is it derived from the server in some way?

If you want to explicitly set the mime type from your template, you can do it with Craft's {% header %} tag:

{% header "Content-Type: application/json" %}

If it is already set via this method, Craft will go with it and not attempt to auto-detect/set the mime-type on it's own.


SQLSTATE[23000]: Column 'targetId' cannot be null I'm getting the following error whenever I try to post a new entry to one of my channels in Craft:

2015/10/26 14:42:36 [error] [system.db.CDbCommand] CDbCommand::execute() failed: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'targetId' cannot be null. The SQL statement executed was: INSERT INTO `craft_relations` (`fieldId`, `sourceId`, `sourceLocale`, `targetId`, `sortOrder`, `dateCreated`, `dateUpdated`, `uid`) VALUES (:row0_col0, :row0_col1, NULL, NULL, :row0_col4, :row0_col5, :row0_col6, :row0_col7).

From what I can tell, the error is being triggered by the asset field in the section. I'm posting a JS created File to the asset field, not a file from a file input (which works fine during testing). The image file being posted is built from a Data URI which is converted to a Blob, and is then converted to a file. This is rather hacky*, but the best way I could find to successfully (as far as I can tell) post an image to Craft.

Is it possible that some important metadata is being left out when the image file is created, that is causing this error? Or is it a case of the image not being saved before the entry in time for this relation to be created, or vice versa?

*My reason for doing this is because the images are from a mobile phone camera, everything is being posted from a Cordova app.

Edit 1:
From the app I'm posting directly to Craft with Ajax using the entries/saveEntry action. But this is being routed via a plugin I wrote to allow me to use JWT based authentication. I've had no issues with this during testing, only when I switched from using a field input to generating the files via JavaScript has this error started occurring.

Edit 1.5:
I've managed to fix the issue. See below.

I've managed to fix the issue. Originally I was converting the Blob to a File, but this was causing the upload to silently fail. So, when Craft tried to create the relation between the asset field and the image, it threw the error above.

Now, instead of converting to a file, I'm leaving the Blob as is but adding additional metadata (Last modified data & name), and passing a file name to the FormData.append() when creating the FormData object.


Reusable content in entries, globals? How do I use/call globals in entries? Trying to insert a simple global called {{ whateveryounameit }} with some text but don't see anything except its name.

Any other ways to display common content across multiple entries?

You call globals with the globals' handle, and the field name of a field in it. So, if you have a text input field named "myField" inside a global with handle "myGlobal", you can call it anywhere in your templates with:

{{ myGlobal.myField }}


Freeform Pro Plugin Mailchimp integration Got issues with Freeform Pro Plugin, no matter what settings I set on status in the plugin the subscriber goes right into the list on Mailchimp even though status is set to 'pending' on plugin both at default and form setting level.No double opt-in verification.

Any ideas guys?

Plus unrelated, the user when sends also gets a notification of what they have sent, we don't want this. And if we ever did, we would want a custom template for it. any help would be great.

I had this same issue. We needed to send a contact information form to MailChimp only if the person opted in to receive e-mails. However, the information would always be sent even if the opt-in box was left unchecked. No idea why. I ended up hiding the opt-in box and then added a "yes or no" field that conveyed whether or not the user wanted to receive e-mails. Hope that help and makes sense!


Send plain text email using EmailModel? I currently have a plugin that's successfully sending email using EmailModel(). The problem is: it's sending a multi-part email with HTML and plain text components. For this particular email, it would be best if I could just send the plain text portion.

Is there a way to disable the HTML segment when sending via EmailModel()?

Currently not.  If Craft sees that there isn't anything specified for the htmlBody property of EmailModel will run the body property though Markdown and set that to htmlBody.


Building a DbCommand to compare two columns on Variants I am trying to compare two fields located on Variants in Commerce. One is the price field and then I also have an original price field which is a custom field. I want to compare and get all variants where the price is less than the original price.

$query = craft()->db->createCommand()
            ->from('commerce_variants')
            ->where("price < field_originalPrice")
            ->queryAll();

return $query;

This is what I have so far but could be way off on this since that custom field is actually on the content table.

Any help would be awesome! Thanks!

Completely untested, but this should return all variants whose price column's value is less than your custom field's originalPrice value.

$results = craft()->db->createCommand()
    ->select('v.*')
    ->from('commerce_variants v')
    ->join('content c', 'v.id = c.elementId')
    ->where('v.price < c.field_originalPrice")
    ->queryAll();


Query entries posted in the past month I’m trying to show only entries for the created in the last month. I’ve taken this from the example in the docs but it ends up showing nothing. There’s 100% entries with a postDate in the last month.
What am I missing?
{% set start = now|date_modify("-1 month")|date('Y-m-d') %}
{% set end = now|date('Y-m-d') %}

{% set newsQuery = craft.entries({
    section: 'news',
    postDate: ['and', ">= #{start}", "< #{end}"],
}) %}

Thanks!

Immediately found a solution!
{% set newsQuery = craft.entries({
    section: 'news',
    after: now|date_modify('0:00 -1 months'),
}) %}


Pagination with if statement date modify How can I incorporate the date_modify into the craft.entries query so that the pagination takes into account this criteria? At the moment the limit is also accounting for past entries and I'm hitting errors whatever I try.

{% paginate craft.entries.section('events').limit(10).order('date asc') as entries %}

    {% for entry in entries if entry.date > now|date_modify('-1 day')  %}

        ...

    {% endfor %}

    {% include "includes/_pagination" %}

You can add it like every other criteria property

craft.entries.date('>' ~ now|date_modify('-1 day')|atom)


Starting & Ending Loops with Eager Loaded Elements Basically, I have two sections of a page. In one section of the page, I want to output the first 8 entries in a loop. In the next section of a page, I want to output from the 9th entry to the end of the loop. The entries that I'm looping through are eager loaded.

This is how I'm doing it right now:

{% set clients = element.clients.find({
    with: [
        ['logo', {
            withTransforms: ['newClientLogoPage']
        },]
    ]})
%}

SECTION #1:
{% for client in clients %}
    {% if loop.index0 <= 7 %}
        DO SOME STUFF

SECTION #2:
{% for client in clients %}
    {% if loop.index0 >= 8 %}
        DO SOME STUFF

Essentially, I'm fully looping through the same entries twice and just starting and ending what is output at different spots using loop index.

Is there a better / more efficient way to start and end my loops at different points without doing two full loops like I am now?

Found this nugget about Iterating over a Subset in the Twig docs about slice:

{% for client in clients|slice(0, 8) %}
    ...
{% endfor %}

{% for client in clients|slice(8) %}
      ...
{% endfor %}

More details about slice.


Any workarounds for image resizing in Craft 2.5 Redactor II? Since imageResizable was deprecated for some apparent reason which I have no idea why they would do that. Does anyone know of a workaround or a plugin/config setting to enable this again?

The only really workable solution I've found is to downgrade Redactor. Fortunately Pixel & Tonic have made this fairly painless with a plugin:

https://github.com/pixelandtonic/RedactorI


responsive image and srcset with Imager Have read this article, but still having issues.

Craft 3.0.4
Imager 2.0.0

My template code is:

{% set image = block.image.one() %}
{% set focalPoint = image.focalPoint | default("50% 50%") %}

{#
  // set transform for floated images
  // override in full width
#}
{% set transformedImages = craft.imager.transformImage(image,
    [
        { width: 400, ratio: 4/3, jpegQuality: 85 },
        { width: 640, ratio: 4/3, jpegQuality: 85 },
    ],
    {
        format: 'jpg',
        allowUpscale: false,
        mode: 'crop',
        jpegQuality: 80,
        interlace: true,
        position: focalPoint,
    }
) %}

{# determine if image floats or not #}
{% if block.imageFormat == "left" %}
  {% set imageClass = "floated-left" %}
{% elseif block.imageFormat == "right" %}
    {% set imageClass = "floated-right" %}
{% else %}
    {# full width #}
    {% set imageClass = "full-width" %}
{% endif %}
{# end floats or not #}

{# full width image here #}
{% if block.imageFormat == "fullWidth" %}

{% else %}
{# floated images here #}
  <img
    src="{{ craft.imager.base64Pixel(16, 9) }}"
    sizes="(max-width: 640px) 640w, (min-width:641px) 400w"
    srcset="{{ craft.imager.srcset(transformedImages) }}"
    class="{{ imageClass }}"
    >
{% endif %}

What I expect to happen is that at widths smaller than 640px an image with a width of 640px is served up, at widths 641px and larger and image of 400pxs is served up.

However at large widths I see the 640px width image.

The outputted code on the front end is:

<img
  src="data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20width%3D%2716%27%20height%3D%279%27%20style%3D%27background%3Atransparent%27%2F%3E"

  sizes="(max-width: 640px) 640w, (min-width:641px) 400w"

  srcset="/imager\uploads\32\love-letters-in-pink-hearts_4460x4460-1_d5a1008e3f8fb9f7c44fa92474183c3e.jpg 400w, /imager\uploads\32\love-letters-in-pink-hearts_4460x4460-1_3edaa49114a08f6f3438bb6daad2e68a.jpg 600w, /imager\uploads\32\love-letters-in-pink-hearts_4460x4460-1_7c3d51f40436135917e37f29c276802d.jpg 640w"

  class="floated-left">

Not sure what I'm doing wrong. Please advise.

It looks like the sizes attribute needs to be tweaked. Absolute image sizes need to be specified in px units, not w.

<img src="{{ craft.imager.base64Pixel(16, 9) }}"
     sizes="(min-width:641px) 400px, 100vw"
     srcset="{{ craft.imager.srcset(transformedImages) }}"
     class="{{ imageClass }}">

The way the browser reads sizes is left to right and picks the first match. So the assumption would be that if the viewport width isn't greater or equal to 641px, then it must be smaller than 641px. So there's no need for (max-width: 640px). The last value is the default size.

Alternately, this could be expressed by declaring the smallest viewport size to largest like this:

sizes="(max-width:640px) 100vw, 400px"

Also, instead of saying "when the viewport is smaller than 640px, use the 640px image", e.g. (max-width: 640px) 640px, what you probably want is 100vw. I'm assuming the image doesn't always stay 640px even when the screen gets smaller. If your design is responsive, the image will scale down with the screen width.

Using 100vw means that when your viewport is 400px wide or smaller, the browser can now choose to download the 400px wide image version. Or if the viewport is 640px wide, the 640px wide image is a better match.

Here's an example on Codepen: https://codepen.io/alexroper/pen/VxGgLj

Another possible reason you're not seeing the 400px size is if you're using a hi-dpi, "Retina" display or similar 4k monitor. The browser picks the best image to display from the available ones in srcset. If you specified the target image size as 400px (CSS reference pixels), but you're display is 2x "Retina" display, the browser will favor using the higher resolution image. The high pixel density of a 2x display can fit 800 pixels in a 400-pixel space. 640px isn't as large as 800px, but it's better than 400px so the browser would choose that image.

So even tho an iPhone 5 has a screen size of 320 × 568 in css reference pixels, the physical pixels are double that (640×1136). Safari will prefer to download the higher res 640px image over the 400px one in the img tag example above.


How to attach a plugin license to a CMS license? I have a Craft license that is not attached to a Craft CMS license and cannot figure out where/how to attach it to one in my Craft ID account so that I can use it in a Craft CMS installation.

To do this, you need to install the plugin on whatever site you want to associate with it - and then enter the license for it under Settings > Plugins.


Modules - CP Template not found I've used this tool to generate a module: https://pluginfactory.io/

So in my constructor, I have

 Event::on(View::class, View::EVENT_REGISTER_CP_TEMPLATE_ROOTS, function (RegisterTemplateRootsEvent $e) {
            if (is_dir($baseDir = $this->getBasePath().DIRECTORY_SEPARATOR.'templates')) {
                $e->roots[$this->id] = $baseDir;
            }
        });

In my init() function I have this

 Event::on(
            Cp::class,
            Cp::EVENT_REGISTER_CP_NAV_ITEMS,
            function(RegisterCpNavItemsEvent $event) {
                $event->navItems[] = [
                    'url' => 'leads',
                    'label' => 'Leads Management'
                ];
            }
        );

When I click the link on the control panel, I will get a Template Not Found error.

My template folder is located at modules/leadsmodule/src/templates

Inside templates I have a file called leads.twig.

I did die() on the $baseDir that it's being set to in the constructor and got the path: modules\leadsmodule\src\templates

I need my control panel item to load a specific template.

What am I doing wrong?

Edit: the control panel URI for my item looks like /admin/leads

Here is my config/app.php

'*' => [
        'modules'   => [
            'leads-module' => [
                'class' => \modules\leadsmodule\LeadsModule::class,
            ],
        ],
        'bootstrap' => ['leads-module'],
    ],

I've tried every combination to load the template I can think of.

In side my modules/leadmodule/src/templates I've placed the following

admin/leads-module/leads.twig

admin/leadsmodule/leads.twig

/admin/leads.twig

/leads-module/admin/leads.twig

/leads-module/leads.twig

/leadsmodule/admin/leads.twig

/leadsmodule/leads.twig

/leads.twig

Still get a 404 template not found: leads when accesses /admin/leads from the control panel

It must be /admin/module-id/leads. So in your case maybe /admin/leadsmodule/leads or /admin/leads-module/leads depending on your ID if you want to access it directly via template route.

Otherwhise you need to create custom URL rules


Section/category setup input Looking for some input on how to setup a Craft site. I have 2 sections of the site containing content grouped by the same set of topics (or categories).

For example, within Services there 6 sub-pages. Resources has 6 sub-pages using the same categories as Services.

In other words there is a page under Services and Resources named Topic 1. In Services the Topic 1 page will contain a description of Topic 1. Under Resources the Topic 1 page will contain PDFs and FAQs related to Topic 1. The PDFs and FAQs would ideally be sorted by a custom order. There are similar pages under Services and Resources for Topic 2, Topic 3, etc.

Recommendations on how to set this up in Craft?

You need to create several inputs and apply them to your topics category group.

Description field
Assets field for PDF's
Matrix field that allows the user to add multiple FAQ's

In your Services detail page get the category from your category input and output the description:

{% set topic =  entry.categoryInputHandle.first() %}
{{ topic.descriptionFieldHandle }}

Next in your Resources detail page grab the category and output the PDF and FAQ's.

{% set topic =  entry.categoryInputHandle.first() %}
PDF
{% for faq in topic.faqMatrixFieldHandle %}
    {# output the different fields you setup in the matrix… #}
{% endfor %}


Where to store asset backups for plugin? I need to store revisions of assets for a plugin I am working on, what is the best / most robust location to store them?

I need the location / files to:

Always be writable.
Not removed when / if craft/storage is cleaned out.
Unaffected by updates or cache being cleared.

S

The only thing that Craft guarantees to be writable is craft/storage (and to a limited extent, craft/config).

But, 99% of things in craft/storage can and will be rebuilt as needed depending on the request, even if the entire folder has been nuked.

You can either work within that context, save your assets as blob's in the database (would not recommend) or in your plugin's installation instructions, make sure that you specify they create a craft/plugins/pluginHandle/writable folder you can save your asset revisions to.


Author list limited to first 100 when assigning to entry? We have more than 100 authors in a user group, but when selecting an author for an entry, only the first 100 are listed in the (a-z) dropdown. Whats the best way to display them all (or up the parameter?)

By default, Craft sets the limit of the ElementCriteriaModel to 100.

If you want to get all/more entries just set the .limit parameter to null or a number:

{% set allUsers = craft.users.limit(null).find() %}

{% set someUsers = craft.users.limit(200).find() %}

A list of all available parameters can be found here: craft.users


What's a Craft way to achieve extra info on specific relationships? For example, say I have two sections:

Services
Locations

I make an entries field called "Services" and add it to the Locations field group, so that on a Location entry you can add n number of services.

What if I want a little bit of extra info that's unique to that particular pairing?

So, I have a location page called "Boston, MA" and a Service called "Window Washing". Using my entries field, I create a relationship on my "Boston, MA" page to the "Window Washing" Service.

However, I want to show a note with this particular relationship that we don't do Skyscraper windows in this location. It's Extra Info for this relationship only and it's variable.

How would you solve this problem in Craft?

One solution I've come up with is to add a Matrix field that has two fields:

Text Input
Entries Field

Add that field to the "Services" field layout. Then you could add a lookup on the "Boston, MA" page when you iterate over related Services. Do a lookup and say, do they have a Matrix entry that is associated with this entry, and pull in the Extra Info as appropriate.


Can I use a Block inside an Include file? I have a _layout.html template which has both an include partial {% include '_partials/_header.html' %} and a block section (e.g. Content) for other templates to extend it.

Can I put another block section (e.g. Breadcrumb) inside the include file and use that in a template which extends _layout.html? So far it doesn't seem to work. If I move the Breadcrumb block from the include template into _layout.html it works fine, and when I move it back the content in the template extension does not show.

I believe it is possible @jack. Take a look at this working demo - http://twigfiddle.com/9rwjeo

Update:

On closer inspection the original example did not work. You can not have a block inside an include how you are describing.

I have update the twig fiddle with a work around though


500 error: uploading files (duplicate primary key) Afternoon all - odd issue where created some new asset folders and adding new files is timing out. If I view the folder in question (on the server) I can see the file has been successfully uploaded but this isn’t reflected in the back-end. Craft 2.4. Console Log is returning a POST /admin/actions/assets/uploadFile 500 (Internal Server Error) response.

Checking the craft logs it is throwing a Duplicate entry '3996' for key 'PRIMARY' error in the craft_assetfiles table. It looks like somewhere between builds/deployments the craft_assetfiles table has got out of sync. I've tried updating the Asset and Search indexes but with no success.

Any thoughts on debugging or resolving?

Okay - have managed to resolve this. Needed to reset the auto increment value in the craft_elements to greater than the max(id) for the craft_assetfiles - not sure how those got out of synch but that seems to have resolved it. Hallelujah!


Why are there now blank entry folders in my image assets folder? There are folders in my images asset folder craft/public_html/images/ named for individual entries (posts).  But, the folders are empty.  This is something new.  Only recent posts are represented.  The actual images for these and all posts are still there, the settings have not changed and everything seems okay. And, it appears I can delete one of these empty folders without negatively impacting the actual post.

Is this a quirk or associated with a recent update and therefore has some purpose?  Should I delete them or leave them?

Thanks

I guess you or someone else made a subfolder in your upload folder. You can do this through Craft itself. This creates a folder you which might be happening in your case. Try adding a new one and see if it happens again. Go to assets and right click a folder to make a sub folder.