Entries limited by date range I'm trying to filter entries on the front end by a date range but no matter what I do I end up with no results, despite there being results in the, temporarily hard coded, date range I am using.

  {% set page = page ?? 1 %}
  {# set search parameter here #}
  {% set search = q ?? '' %}
  {# stage #}
  {% set stage = stage ?? '' %}
  {# date #}
  {% set start = now|date_modify('-16 week')|atom %}
  {% set end = now|date_modify('-1 week')|atom %}

  {% set entryQuery = craft.entries
    .section('projects')
    .limit(limit)
    .stage(stage)
    .startDate(['and', '>= #{start}', '< #{end}'])
    .search(search) %}

    {% for entry in entries %}
      {% include '_includes/project-listing-card' %}
    {% endfor %}

The code above sets some parameters based on the url and defaults. Without the .startDate line this outputs entries as expected. However once I add in the startDate (a date field) nothing gets output.
How do I output entries that are in the date range?

String interpolation in Twig only works with double-quoted strings.
Change the .startDate line to .startDate(['and', ">= #{start}", "< #{end}"]) and it should work.


How to Get Rich Text field in Plugin? I have a 'details' rich text field in my User section. How can i get it in my plugin controller in an array.
I tried getting it by

 $userInfo[] = array(
  'username' => $user->name,
  'details' => $user->details,
)

I get an array like this

        Array
        (
        [0] => Array
            (
                [username] => Username
                [details] => Craft\RichTextData Object
                    (
                        [_pages:Craft\RichTextData:private] =>
                        [_rawContent:Craft\RichTextData:private] => Lorem Ipsum is a dummy text
                        [content:protected] => Lorem Ipsum is a dummy text
                        [charset:protected] => UTF-8
                    )
                )
            )

I'd be inclined to use the public methods for this.
$user->detail->getRawContent();
or
$user->detail->getParsedContent();
etc.


Localhost can't connect to plugin store or updates (WAMP Server) I've now tried installing Craft on multiple PCs to run a local dev environment, but keep getting the same problem. It installs fine, the System Report shows all green,  but when I first load the Dashboard I get the message "An unknown error has occurred" and it fails to fetch Craft News items or updates, and then on the Plugin Store it states "The Plugin Store is not available, please try again later."

I've tried playing around with my Apache setup, but honestly I'm not particularly knowledgeable in that area.

All PCs have been running Windows 10, the latest version of WAMP server, PHP 7.2, and "latest" version of Craft (though it's now two installs behind, which is why I know the updates aren't working despite stating that I'm "up to date").

Live version of the site is working perfectly after upload via FTP, and I've tried reinstalling several times.

You need to download the CA certificate for curl and add it to your php.ini


Auto Post to Facebook/Twitter I've looked everywhere for this functionality and am very surprised that I can't find it...

Is there a plugin that allows auto posting of entry content to Facebook/Twitter/Other social media channel when the user hits Save?

If there isn't, then I'll build one.

I wrote a plugin that posts to Buffer.com (which is free for up to very reasonable levels of activity).  Buffer in turn allows you to post to Facebook, Twitter, LinkedIn, Google+, etc.:

https://github.com/khalwat/buffer

I use it on several sites to do exactly what you describe.


Transitioning local Craft site to AWS EC2 First post here and I am a complete newbie when it comes to Craft and any kind of server config but I am trying to learn.

I am trying get my Craft site that I built locally up to a server today.

I followed a pretty detailed guide about setting up EC2 for craft here:
https://solspace.com/blog/spinning-up-a-craft-cms-development-site-on-amazon-ec2

The issue I'm running into is that when I go to my EC2 URL I'm getting a

  "Service Unavailable

  Our site is temporarily unavailable. Please try again later."

Then trying to login, I get a

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

With devmode on and looking at the console, its throwing me this error:

  "install:82 [16:36:40.799][error][exception.Craft\DbConnectException]
  exception 'Craft\DbConnectException' with message 'Craft can’t connect
  to the database with the credentials in craft/config/db.php.' in
  /var/www/craft/app/etc/behaviors/AppBehavior.php:855"

So clearly Craft is unable to find the database that I created locally but I'm not really sure how to fix this.

My db.php

// The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
'server' => 'localhost',

// The name of the database to select.
'database' => 'mydatabasename',

// The database username to connect with.
'user' => 'root',

// The database password to connect with.
'password' => 'root',

// The prefix to use when naming tables. This can be no more than 5 characters.
'tablePrefix' => 'craft',

Any help would be greatly appreciated!

Figured out the issue. I had one character off in my MySQL database name versus what I was telling craft it was called in the db.php file which is why it was failing to access it. User error prevails again!


How can I get the server's timezone in a Craft plugin? I'm setting up cron jobs from my plugin and I need to format the date in the server's time zone. It looks like Craft is overriding the timezone set in php.ini because PHP's date_default_timezone_get() always returns UTC. Is there another way to get the actual timezone set on the server?

Use ini_get('date.timezone').

Source: http://php.net/manual/en/function.ini-get.php


How to define section parent page? I have a structure section with entry url format: "products/{slug}".
All entries have they urls like "/products/category1/subcategory1/product1".

Currently, I have a header navigation which opens product category pages like "products/category1".What is the preferred way to define "/product" page?

You have to select the "level" in the structure. Im guessing the products are always on level 4? If so you could try this:

{% set entries = craft.entries.section('yourSectionHandle').level(4) %}

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


Can I downgrade my craft version from Client to Personal using the CP? I have already downgraded from Craft PRO to Craft Client and am wondering if I can downgrade again from Craft Client to Craft Personal as the project I'm working on does not need anything more.

Yes you can. If you click the Settings icon in Craft, at the bottom of the screen you will see a box that reads:

  Upgrade Craft to take your site to the next level. Show me.

Click on that and a window will pop-up with the versions of Craft you can install. Yours will look like this:

Just click the Uninstall button and you will be downgraded to Craft Personal.


How to use onDeleteEntry? I currently have a plugin which needs to do things on save and delete entry events. My save entry code is all working perfectly but the onDeleteEntry code doesn't ever fire when I delete an entry.

I have tried using the event both ways mentioned in the documentation

craft()->entries->onDeleteEntry = function(Event $event) {
$entry = $event->params['entry'];
//etc etc
};

and

craft()->on('entries.deleteEntry', function(Event $event) {
$entry = $event->params['entry'];
//etc etc
});

both of these are inside the init function.

Does anyone know if there is a particular way this event needs to be used that differs from the onSaveEntry event, which works fine?

Here's a link to the events reference https://craftcms.com/docs/plugins/hooks-and-events#events

I recently found that if your deleting an entry on the entries list, you need to use the onBeforePerformAction event. Then break this down, like J Thomas states on this -

Get the type of action and the elements(s) that an action is being performed on when listening to elements.onPerformAction?


Craft isn't regenerating the image transform when the focal point changes I've got a basic image transform in a template:

{% set crop = {
    mode: 'crop',
    width: 560,
    height: 550,
    quality: 80
} %}

<img src="{{ image.getUrl(crop) }}">

Once the transforms are generated for a page, it seems like changes to the focal point don't trigger a regeneration of the image transform. Altering the template code (eg. from quality: 80 to quality: 79) does trigger the regeneration of the image.

Is this expected behavior?

Changing a focal point will delete all the transform files as well as transform index entries, so I suspect that you're just seeing cached data.

The reason why it works when changing quality is that that will actually affect the path where the transform is located, so the browser will actually have to look for the new file instead of assuming that the cached version is safe to use.


How to edit a global footer link In the footer at the bottom of my page, www.soldierswish.org, there are two links for 501c3 and Form 990. Is there no way to edit these from the GUI? How do I edit these links?

Look under Globals in the Control Panel, which is the likely place for such links. If you do not see it, either you do not have permissions OR there are no Globals. Assuming you do not see them, Robin's suggestion about contacting the developer is the next step.


Is there a way to check if entry is selected in relationship? This project has a lot of user stuff. I need to display display different sections based on if the current user is in a field.

Is there a better/faster way than looping through and checking if every user matched the current user?

{% for approve in entry.docsApprovedBy.all() %}
   {% if approve.id == currentUser.id %}...{% endif %}
{% endfor %}

You should read the docs about relations

relatedEntries = craft.entries.relatedTo({targetElement: currentUser, field: 'docsApprovedBy'}).all()


Set Variables from the Matrix Field - SEO quick question.

{% for block in entry.matrix %}
    {% if block.type == "seo" %}
    {% set descr = block.metaDescription %}
    {% endif %}
{% endfor %}

{% if descr is defined %}
    <meta name="description" content="{{ descr }}" />
{% endif %}

meta description won't show up? what am I doing wrong?

Twig's for function is scoped. This means that variables defined inside of it will not be accessible outside the loop.

What you need to do, is to declare the variable with an initial value before the loop:

{% set descr = null %}

{% for block in entry.matrix %}
    {% if block.type == "seo" %}
    {% set descr = block.metaDescription %}
    {% endif %}
{% endfor %}

{% if descr != null %}
    <meta name="description" content="{{ descr }}" />
{% endif %}

This works, because in Twig the inner scope (i.e. your loop) will have access to variables belonging to its parent scope, but not vice versa.


How Can I Include a Conditional for First Type of Matrix I want to include a conditional for when the 'Text' block type is returned for the first time in a loop. In css it would be first-of-type.

Here's what I have at the moment:

{% if type == 'text' and loop.first %}

{% endif %}

In this instance my text block type is loop index 3 but I want to adjust the conditional because it is the first text type in the matrix field.

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

{% set firstTime = true %}

{% for block in entry.matrixField %}

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

        ...Do something once...

        {% set firstTime = false %}

    {% endif %}

{% endfor %}


User and Admin email notifications I may be missing something really obvious in the docs - so sorry if I have - but is there a way to send both the user (sender) a notification email, and the admin a different notification email?

Something like what I want has been hinted at: Sprout Forms CC

I know I could set multiple email addresses in the notifications option: Sprout Form > Forms > My Form > Notifications (tab) > Email Recipients (field) but the issue I have is how can I dictate which template is used?

I'm happy to set/use the default options for the Admin email, if you could point me in the right direction for a custom user email option, that would be great.

Sprout Forms supports multiple Notification Emails (as of Craft 3) and multiple Email Template. Sprout Forms also now supports CC and BCC functionality.

Create a new Notification Email on the Sprout Forms->Notifications tab. Each Notification Email has a setting for the Event that you would like to use to trigger it. You can select the "When a form entry is saved" event to trigger an email when a form submission is saved.

While there are numerous ways to trigger an email to both an admin and the user submitting a form, two common methods are:

Setup a single Notification Email and set the To field to the handle of a custom field that has the users email, such as: {email} and set the BCC field to your email address of the admin who you wish to receive it as well. You can separate multiple recipients using a comma-delimited list.
Setup two Notifications Emails and adjust the messages of each to each respective audience. You can create custom, company-branded Email Templates for the user-facing email. Impress them and set expectations for any follow-up communications. Send a workflow-oriented email to the admin, showing all data submitted in the form and linking to any next steps the admin may have to take after the email is received. The default Basic Notification (Sprout Forms) Email Template will loop through and display all values of the Form submission.

Legacy Answer:

In Craft 2, you are correct that Sprout Forms can send multiple notification emails to both admins and users, however the default Sprout Forms notification currently only supports a single template.

It's on our list to consider updating this default behavior. For now, your best options are:

Send the same email to both users and admins.
Add Sprout Email to the mix which integrates with Sprout Forms and allows you to customize as many emails and templates as you'd like and trigger them on the Event: When a Sprout Form Entry is submitted


Validate fields in Solspace Freeform plugin I have been using Solspace Freeform plugin (Lite edition) with Craft 3.
However, I cannot find how to develop validations for the form.
Could you tell me how to develop form validations?
(E.g. postal code, password)

You could use the regex field (not sure if that is available in the lite edition). In that field you could put in regular expressions to evaluate the data entered and force an error if the evaluation doesn't work.
For example you could enter this as the regex patter to prevent a field from accepting special characters and numbers:
^[a-zA-Z\s.-_']+$
Freeform also has ways to run validation from either a module or client side with javascript.
Via a module or plugin:
https://docs.solspace.com/craft/freeform/v3/developer/form-events.html#on-validating-the-form
Via JS:
https://docs.solspace.com/craft/freeform/v3/developer/js-plugin.html#adding-callbacks


How to extract a list of "copy password reset urls" for all users? We are migrating users from a e-commerce site to a new craft commerce 2.x site.

Apparently it's a little too confusing for our customers to use the "forgot password" link to obtain a new password.

So our idea was to send them an email with their username and a link where they can directly set their password.

e.g. "user1", "https://mysite.com/actions/users/set-password?code=qwaZDk6mSa0tbnLBx8U4WkTnTBclK1ZZ&id=779e05ca-5c39-4f66-a56c-9a431bd0b355"

Is it possible to obtain these links programmatically.

We have about 800 users, so copy/pasting them would be very tedious.

any hints?

Cheers
Stefan

Given a list of elements/User that you want to get the password reset URL for, you can loop through them and call this for each one:

$url = Craft::$app->getUsers()->getPasswordResetUrl($user)'


Craft Redis Cache - Get Time Left? Is it possible to find the seconds left / TTL when retrieving cache (when set to Redis) via plugins? I'm using short-lived cache (~600 seconds) to put users on "cooldown" to limit how often they can create new forum topics, by creating a user-specific cache whenever they create a topic. Then I can check and see if this cache exists when they create a new topic.

When getting the cache like:

$cache = craft()->cache->get( $cacheKey );

If it returns true (exists,) I'd like to be able to tell the user how long they need to wait until they can post again (like Reddit.)

I've tried methods like

$cache->ttl; // doesn't work; not an object
$cache['ttl']; // doesn't work, no 'ttl' key

Maybe I am missing something in the Cache Service Doc? Or is this meta information simply not available?

Any information would be awesome. Cheers!

Craft is piggybacking off of Yii's caching functionality for 99% of this and their cache classes don't expose any type of TTL functionality.  My guess is that because of all the different caching providers they support (memcache, xCache, WinCache, ApcCache, etc.), it looks like Redis is the only one that has this sort of functionality.

There isn't a clean way for us to add this to Craft itself, so I think a proper fix would be to add it to Yii, but considering Yii 1 is in bug fix more and not getting any more enhancements and Yii 2 has dropped support for Redis, that seems unlikely.


Why if I change ie. drop down value, all entries needs to be resaved to take changes? How can I prevent it? And why clearing cache is not enough?

Dropdown fields (and other simple option-based fieldtypes such as Radio Buttons, Checkboxes and Multi Select) are pretty dumb.

By design, whenever an Entry with a Dropdown field is saved, Craft simply grabs the selected value for that Dropdown field and stores it in the database for that Entry. Unlike relational fields such as Assets or Categories, there's no "connection" (i.e. relation) between the selected value being stored, and the Dropdown fields' option where the value was pulled from – this means that if you later decide to rename a Dropdown fields' option value from e.g. "foo" to "bar", the selected value for any existing entries will not change/update. In other words, any entries that had "foo" selected, will still have "foo" stored as their value for that particular field, even if that option doesn't exist anymore.

The easiest way to bulk update entries' selected Dropdown values is probably to execute an SQL query.

Something like the below should work (the following example would update the selected value for a field with the handle myDropdownField from "foo" to "bar", for all entries that have "foo" selected):

UPDATE craft_content SET field_myDropdownField = 'bar' WHERE field_myDropdownField = 'foo';

To run this query, you'll need some sort of SQL client – for Mac, Sequel Pro is very decent, and free. You can also use something like Adminer.

Oh, and don't forget to back up your database before running any manual SQL query, and to clear out your caches after you're done.


CSS is not loading on staging server I'm quite new to server config, so this might be a simple mistake. I have a local environment setup on my computer that works just fine. I uploaded my project to my staging server at AWS and the only thing that loads is the index.html in my craft folder. For some reason it gives me a "The requested URL /css/bootstrap.min.css was not found on this server" error for every folder or file I have inside of public folder.

<?php

/**
* General Configuration
*
* All of your system's general configuration settings go in here.
* You can see a list of the default settings in craft/app/etc/config/defaults/general.php
*/

return array(
);

My craft folder in my staging is at: /var/www/craft-portfolio/

My Public folder is at: /var/www/craft-portfolio

The web root is the public folder that is /var/www/craft-portfolio/public

There are multiple ways to set the URLs to your files. I don't know if I got your folder structure right. But let's suppose that your web root is set to
/var/www/craft-portfolio/public/,

your CSS folder is
/var/www/craft-portfolio/public/css/

and your Craft folder (actually not relevant) is
/var/www/craft-portfolio/craft/.

Root-relative URL

Root-relative URLs start with a / character.

<link rel="stylesheet" href="/css/build.css" />

If you are using multiple environments, the path from the web root to your file has to be the same on each environment.
Something like this won't work with root-relative URLs:

http://mysite.com/css/build.css
http://192.168.178.20/projects/mysite/css/build.css

Absolute URL

Add the complete URL of the CSS file to the link tag:

<link rel="stylesheet" href="http://mysite.com/css/build.css" />

You can also use Craft's global siteUrl variable. To do that define the site's URL (http://mysite.com/) in Settings → General in the Control Panel and add the variable to your tag:

<link rel="stylesheet" href="{{ siteUrl }}css/build.css" />

If you want to use the variable in a multi-environment setup, define it in your general.php file (this overrides the CP settings):

return array(

    '192.168.178.20' => array(
        'siteUrl' => 'http://192.168.178.20/projects/mysite/',
    ),

    'craft.dev' => array(
        'siteUrl' => 'http://craft.dev/',
    ),

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

Just be careful if you want to use this on a multilingual Craft site. If you have multiple locales configured, siteUrl will be set to each locale's site URL, which might point to different folders.
You can avoid this by setting a custom variable (eg. baseUrl) in your general.php file:

'environmentVariables' => array(
    'baseUrl'  => 'http://example.dev/',
)

and then use the absolute URL like so:

<link rel="stylesheet" href="{{ craft.config.environmentVariables.baseUrl }}css/build.css" />


SproutForms Problem Getting Update Feed I noticed this morning a deprecation error popped up for SproutForms.  I have version 2.2.2 (which I believe is the latest).  Here's the deprecation error:

Message
PathService::setTemplatesPath() has been deprecated. Use TemplatesService::setTemplatesPath() or TemplatesService::setTemplateMode() instead.

Origin
/home/xxx.com/craft/app/services/PathService.php (321)

I also am showing this in my craft error log:

Level   error
Category    application
Message There was a problem getting the update feed for “Web Forms”, so it was skipped: [curl] 35: [url] https://sprout.barrelstrengthdesign.com/craft-plugins/forms/releases.json

These two items are unrelated.

First, there's no need to worry about the deprecation errors.  We actively maintain our plugins and will have them resolved before they should have any effect on general use of our plugins. We've made a feature request to Craft to consider to reduce the prominence of the deprecation message, as it generally just causes unneeded alarm.

Second, the releases message is probably due to us currently having an SNI SSL certificate installed and some older server configurations choke because they don't know how to deal with them. The error probably indicates that you may be running fairly old software on your server.

If you're curious, I was told by Craft support:

  Technically there are 3 things a server needs for it to be able to
  recognize SNI SSL certs.

  1) Using a version of cURL that supports it, at least 7.18.1 (8 years
  old: https://curl.haxx.se/changes.html)

  2) Using a version of cURL compiled against a library that supports
  SNI, e.g. OpenSSL 0.9.8j (depending on the compilation options some
  older versions. 7 years old:
  https://www.openssl.org/news/changelog.html)

  3) Using TLS 1.0 at least (not SSLv3)


Why is this Twig code generating large numbers of DB queries? I have a Twig include that generates a News Archive side-bar. It works great, but I've just noticed that on a particular project it's contributing in the region of 800 DB Queries when caching is off.

What have I missed about the mechanics of the group filter? Because I can see no other reason why this should generate more than one query?

{% cache globally %}
    {% set allEntries = craft.entries.section('newsItems').limit(null).all() %}

News Archive

            {% for year, entriesInYear in allEntries | group("postDate | date('Y')") %}

                    {{ year }}

                        {% for month, entriesInMonth in entriesInYear | group("postDate|date('m')") | reverse(true) %}

                                    {{ entriesInMonth[0].postDate|date('F') }}

                        {% endfor %}

            {% endfor %}

{% endcache %}

The solution is below.
EDIT: only for MySQL 5.7.4 and lower! Higher versions break.

For whatever reason, the mechanics of the group filter in this case was producing a new query for every Entry. Below, resolves this by doing the same job in a more performant way. I'm not entirely sure of the mechanics of how this works, but the answer was supplied over on the Discord support channel and I thought it worth cross-posting to here. Thanks Sebastian Lenz!

{% cache globally %}
    {% set postDates = craft.entries({
        section: 'newsItems',
        select: 'postDate',
        limit: null,
        groupBy: ['DATE_FORMAT(postDate, "%Y-%m")'],
    }).column() %}

News Archive

            {% for year, postDatesInYear in postDates|group("object|date('Y')") %}

                    {{ year }}

                        {% for month, postDatesInMonth in postDatesInYear|group("object|date('m')")|reverse(true) %}

                                    {{ postDatesInMonth[0]|date('F') }}

                        {% endfor %}

            {% endfor %}

{% endcache %}


Setting User Permission to hide products of other user I have a model where there will be many users. Each user has dashboard access and can add there products.. this all is done, but what I want is one user doesn't see other user products. Right now a user can see all products uploaded by all users. Currently Craft CMS doesn't have permission settings to hide entries of other user as they have for channel entries.. but I need that. Can anyone help me how can I achieve that. Any ideas would be helpful. Thanks in advance

This sounds like a feature request really.  And/or possible a use case for Craft 3s forthcoming multi-site features.  Although C3 + Commerce for it is a ways off yet (6 to 9 months apparently)

You could perhaps use something like a custom field for the 'owner' of each product, and Zenbu to set up filtered views for each of the editors (just guessing, I've not used Zenbu personally)

https://zenbustudio.com/software/zenbu-craftcms


Is it possible to disable dev output in a template when devMode is true? For example the template just outputs JSON, which breaks when Craft's devMode logging is added.

You can create a simple plugin with an init() method like so:

public function init()
{
    craft()->log->removeRoute('WebLogRoute');
    craft()->log->removeRoute('ProfileLogRoute');
}

That will prevent the extra logging and profiling information to be output in the browser's console when devMode is enabled.


How to compare just the date part of a dateTime field? Ok I want to list event entries based on the start date of those events.

I have a route set up which provides the date in the same format as held in the start date field. But trying to compare this with:

{% for entry in craft.entries.section('events').startDate(date) %}

to pull out only entries for the specified date fails as the date variable only holds the date portion of the startDate field i.e. 2015-10-02 and not the time segment.

So is there some way I can format this call so that the comparison is like with like without the time segment. I have tried a few things with filters but nothing is working.

Cheers

I'm not 100% sure I'm reading your question correctly, but here goes:

I'm assuming you're getting the date as a string as a route param (maybe you shouldn't call it date though, as that is a function in Twig), I'll call that dateTime here:

{% set dayAfter = date(datetime) | date_modify('+1 day') | date('Y-m-d') %}
{% set entries = craft.entries.section('events').startDate(['and', '>= '~datetime, '< '~dayAfter]) %}

What's happening is you get a date, then you add one day to that date, then find all entries that have startDate greater than or equal to the date you're looking for, and less than the day after, thus getting all entries for that particular date.

This might be over engineered though, and there might be a way simpler way to do this...


Fatal error: Class 'Craft\FileCache' not found when trying to install I've been trying to install Craft on a DigitalOcean server. I used DO's LAMP stack application on Ubuntu 14.04 and downloaded the latest version of Craft. After uploading everything to my web root (the default is /var/www/html so the craft folder is at /var/www and the contents of public are at /var/www/html), whenever I try and go to the website, I get an error saying: "Fatal error: Class 'Craft\FileCache' not found in /var/www/craft/app/services/CacheService.php on line 59". If I go to example.com/admin, I get an Apache 404 error. If I try example.com/index.php/admin, I get the same fatal error as I described above.

I know this means I need to enable mod_rewrite (I've already renamed htaccess to .htaccess), but I should still be seeing something. I'm not sure what to do about the fatal error. I've redownloaded the Craft files to be sure nothing got corrupted in the original download, but I still have the same problem. I've also tried it on a server I have from A Small Orange and got the same thing. I also changed the required folders' permissions to 777 just to rule out any permissions problems.

Any ideas? Thanks!

After checking out the craft/app/etc folder, I noticed the cache folder was missing. It turns out that the problem was with my FTP client ignoring folders named "cache". So really a dumb mistake on my part.

Thanks for your help @BradBell!


Updating the Database for plugin settings I have another plugin development question.

I am now trying to learn how to work with the database.  To that extent, I have the following code:

On the templates/settings.html page I have the following code:

{% import "_includes/forms" as forms %}

{{ forms.radioGroup({
    label: "Radio Group Label"|t,
    instructions: "Radio Group Instructions"|t,
    name: 'radioGroupName',
    options:{ "option_1" : "option_1", "option_2" : "option_2"},
    value: settings.radioGroupName
}) }}

On the records/PluginNameRecord.php page, I have the following code:

<?php
namespace Craft;

class PluginNameRecord extends BaseRecord
{
    public function getTableName()
    {
        return 'pluginname';
    }

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

}

And here is the code for the models/PluginNameModel.php file (I don't know if this is relevant or not, but I'm including it just in case):

<?php
namespace Craft;

class PluginNameModel extends BaseModel
{

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

Now, I have tested this and it creates a table and column in mysql.  However, I cannot update the data in the database.  That is to say, if I select option_2 nothing happens in mysql.  The same default value of option_1 still shows up.

Can someone please let me know what I am doing wrong?

Thanks,

Moshe

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

In your main plugin file (PluginNamePlugin.php):

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

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

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

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

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

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

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

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

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

...and in your template:

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

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


How can I upgrade to version 3.0 as a user? I am an end user and see there is a 3.0 version. Can I upgrade for free and what steps do I need to take to do that?

Upgrade instructions are found here, although i wouldn't recommend it as an end user. You want to backup your database in case something goes wrong, change file paths/content, etc. Even if you have the access and knowledge to run the scripts, you should have a developer do this for you.


Where do you set PEM file passphrase for Craft CMS Push Notification Plugin for an iOS app? Does anyone know where to set the passphrase for the PEM file that is configured in the Push Notification Plugin for Craft CMS?

I have created a new app and set the Certification Location to the PEM file location. I have tested on the server to confirm that the certificate and key files work. However, when I try to send a new alert -- I get the following error:

stream_socket_client(): Unable to set private key file

Which I'm sure is due to the fact that I haven't told it what the passphrase is. However, I can't find any documentation that explains where to put this configuration setting.

Any help is greatly appreciated.

Plugin Github Reference: https://github.com/boboldehampsink/pushnotifications

From my research and testing, it looks like this plugin doesn't offer the option to set a passphrase for the PEM file. I had to create a new PEM file that doesn't require a passphrase in order to send a successful alert.


Single type for entry submission on error loses entry object I have created a contact form inside a single entry type 'contact' for front end submissions.
This lets me display editing options for title and body and display the form.

When submitting the form, the entry object ( eg entry.title ) disappears and no title or body  content is shown - just the form with its corresponding errors.

So submitting it seems to lose the entry - is this because it is returning the saved entry model and not the single that it is on?

From the README:

  If there is a validation error on the entry, then the page will be reloaded with an entry variable available to it...

You can override the variable name by setting the entryVariable config setting, as follows:

<?php

// File: craft/config/guestentries.php

return [
    'entryVariable' => 'guestEntry',
];

Once you've done that, the page entry model will be available as entry, and the "guest entries" entry model (containing any validation errors) will be available as guestEntry.


Plugin to create an image transformation for an external image (non-Assets field) In reference to this post Can I apply an image transformation to an arbitrary image (non-Assets field)? does anyone have an example of the markup used to create the plugin to do this?

I need to create a transformed thumbnail from a Vimeo/YouTube URL, but I am having difficulty creating the plugin.

I have created the following function:

public function videothumb($imageSource)
{

  $image = craft()->images->loadImage($imageSource);
  $image->setQuality($quality);
  $image->resize($transform->width, $transform->height);
  $image->saveAs($targetFile);

}

And I am calling it with:

{% set thumb = {
    mode: 'crop',
    width: 100,
    height: 100,
    quality: 75,
    position: 'top-center'
} %}
{{ craft.thoughtful.videothumb('http://thoughtfulweb.com/images/_halfPageStandard/Thoughtful-Indiana-Jones.jpg', thumb) }}

I keep getting an error saying:

No file exists at the path “http://thoughtfulweb.com/images/_halfPageStandard/Thoughtful-Indiana-Jones.jpg”

Clearly I am missing something. Any pointers would be greatly received.

PS. I know the file path does not point to a video thumbnail. It’s just for reference.

The ImagesService's loadImage() method is designed to read image files off of the local file system only, not URLs – hence the appropriate error message; Craft treats your URL as a local filepath and that file obviously doesn't exist.

To apply transforms to an image on a remote host, you'll have to jump through a few hoops. First, you'll need to download the image from the remote URL to your local server – the easiest way to do this is using PHP´s file_get_contents method – before creating and storing the image file (the best way to do that is by using the IOHelper class' createFile and storeFile methods). At that point you'll have an image file on the local filesystem and a valid filepath to use for the ImageService in order to apply your transform.

Along the way, you'll need to take care to retain the remote image file's extension (i.e. jpg, gif, png or the like), construct valid filepaths for the downloaded image and the transformed image(s), handle caching for the external file (avoiding a situation where you'll have the server downloading the remote image on every pageload), testing for existing transforms (to avoid needlessly re-transforming the image on every pageload) etc.

My advice: Unless you absolutely need to (or want to) write your own plugin, you should use the excellent Imager plugin – which is able to transform images from external hosts (i.e. URLs) out of the box. Here's how you could use Imager in your template:

{% set thumb = {
    mode: 'crop',
    width: 100,
    height: 100,
    quality: 75,
    position: 'top-center'
} %}
{% set image = craft.imager.transformImage('http://thoughtfulweb.com/images/_halfPageStandard/Thoughtful-Indiana-Jones.jpg', thumb) %}
{% if image %}
<img src="{{ image.url }}" />
{% endif %}


Craft CMS HTML Email Template I have a contact form that works using Postmark and Contact Form plugin.

I'm trying to find a way to edit the format of the email that I'm getting when someone sends a message via the website contact form.
E.g.

Subject:
Message from: {{ name.field }}

Full name:
{{ name.field }}

Email:
{{ email.field }}

Department:
{{ department.field }}

Message:
{{ message.field }}

I can see that there's a "HTML Email Template" option in Settings > Email. But I couldn't find any documentation.

The "HTML Email Template" option in Settings > Email in the Craft control panel is completely unrelated to the Contact Form plugin.

If you want to change the body of the email that gets sent out, you'll need to write a plugin that listens to the beforeMessageCompile event as documented here: https://github.com/pixelandtonic/ContactForm#the-contactformbeforemessagecompile-event


Issues with Twig template includes when rendering from a service called from a CP-triggered event I have a listener for the entries.saveEntryevent that is calling a service, which generates an email from a rendered template. The template is attempting to import macros.

MyaddonPlugin.php::init()

craft()->on('entries.saveEntry', function(Event $event) {
    if ($event->params['isNewEntry']) {
        craft()->myaddon_emails->generateEmail($event->params['entry']);
    }
});

Myaddon_EmailsService.php::generateEmail()

$emailHtml = craft()->templates->render('myaddon/email');

plugins/myaddon/templates/email.twig

{% import '_macros/mymacro' as mymacro % }

When I attempt to run this I get this error:

Unable to find the template “_macros/mymacro”.

When running the same service/render code from a Controller, everything works. It seems like there is a difference with how paths are set or handled in a Controller vs. an event handler. I tried manually setting the template path based on this page, but same results.

Any thoughts on how to resolve this?

Thanks in advance!

Not 100% sure what is going wrong here, but here is what I would do to debug this on my end:

Simply output the current path the template parser is using in the controller and event handler to see the difference in the values

var_dump(craft()->path->getTemplatesPath());
exit();

If the values are different, you can override the value to do your parsing as your need it like so:

// Get the current path and save it
$oldPath = craft()->path->getTemplatesPath();

// Set your desired template path
craft()->path->setTemplatesPath('your/new/path');

// Render your template and pass some data to it that will be parsed
craft()->templates->render('your/template', $data = array());

// Set the old path so Craft can resume as normal and you don't break stuff
craft()->path->setTemplatesPath($oldPath);

One other option is to try to include your macro like so:

{% import 'myplugin/_macros/mymacro' as mymacro % }

I basically do the exact same thing you are doing with Postmaster for Craft. I include my own macros, parse templates and strings during event handlers, it all works perfectly for me using the technique I outlined above. Feel free to take a look at my code if you want to see some more advanced examples of this.

On a side note, I bet Postmaster will do exactly what you want to do in regards to sending an email for new entries. You should give it a shot, it has loads of additional features I bet you could use. No less, I do help this solve your problem either way. Sorry this wasn't really an official answer or a guaranteed fix, but I gave it my best shot without seeing all of your code.


Get Assets in JSON with ElementAPI I'm trying to integrate the ElementAPI plugin into my site. Essentially, I need to output all of the assets within the website into a JSON file that I can link to in the load manifest of PreloadJS. If you read the docs here, you'll see that the images can be loaded from an external JSON file.

Here's what I've been working with so far:

<?php
namespace Craft;

return [
    'endpoints' => [
        'assets.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'news'],
            'transformer' => function (EntryModel $entry) {
$images = [];
        foreach ($entry->featuredImage as $image) {
        $images[] = $image->url;
        }
                return [
                    'image' => $entry->image
                    'jsonUrl' => UrlHelper::getUrl("assets/data.json")
                ];
            },
        ]
    ]
];

So, to sum up, what I'm needing to do is build an API that will get a list of all the assets used in my site and output them into a JSON file that I can link to in a JS file as part of the PreloarJs plugin. This would make my preloader dynamic and allow me to keep my javascript external, rather than getting the assets inline, which I have been doing.

Thanks!

Something like the following should work:

// elementapi.php
return [
    'endpoints' => [
        'assets.json' => [
            'paginate' => false,
            'elementType' => ElementType::Asset,
            'criteria' => [
                'limit' => null,
            ],
            'transformer' => function(AssetFileModel $asset) {
                // Set `generateTransformsBeforePageLoad` to `true` to have Craft generate transforms at runtime
                craft()->config->set('generateTransformsBeforePageLoad', true);
                return [
                    'title' => $asset->title,
                    'url' => $asset->url,
                    'thumb' => $asset->getUrl(['width' => 100, 'height' => 100]),
                ];
            },
       ],
    ]
];

One small gotcha: By default, Element API will paginate results. To avoid that, you can add a 'paginate' => false, parameter to your endpoint.

Another small gotcha: If you want to return transformed Assets (e.g. a thumbnail version), you can pass a named or inline (array) transform to $asset->getUrl(), but you'll need to set the generateTransformsBeforePageLoad config setting to true at runtime in order to have Craft actually generate the transforms when the endpoint is requested.

Finally: Depending on the number of Assets and Entries, you might see some performance issues with this method (especially if you're going to include transforms and don't paginate the results), so it'll probably be a good idea to cache the assets.json output in some way.


Identifying users and site permissions when logged in If I'm logged in as a user in user Group A, how can I tell which site I am currently viewing?

I want to be able to create a multilingual site switcher. But my setup is complex.

I have Company A, User A is in  Group A

Company A Russian, User A is in Group A

Company A Hindi, User A is in Group A

I want to be able to let the user choose the Russian version of the current content. Same for Company B User B in Group B, etc. etc.

I built my site switcher like this:

https://www.thebasement.be/language-switcher-for-craft-3/

You will have to define an array for your site variables in the general.php for each environment:

'siteUrl' => array(
  'default' => 'http://yoururl/',
  'english' => 'http://yoururl/en/',
 ),

You can also extend the user with a language field and let him save his preferred language with a simple form like the user profile form from the Craft 3 docs.


Adding or overriding locales in Craft 3 I am looking for a way to add new locale files or override existing ones.

Basically a Craft 3 version of this: https://craftcms.com/support/adding-additional-locales

I've tried the way described here: https://github.com/craftcms/locales

But that does not seem to be picked up by Craft 3.

I've tried the way described here: https://github.com/craftcms/locales but that does not seem to be picked up by Craft 3.

Haven't actually tested this, but looking at the code I think it should work.

You'll need to disable the intl extension from being loaded on your box (usually done in php.ini) because if Craft sees that's available, it will use that automatically.

If it's not available, it falls back to config/locales, which is where you should be able to put your "custom" locale.


Getting server-side feedback when submitting forms with jQuery Form plugin I've got a few simple front-end forms that users can use to update their profiles. I'm using the combo of the jQuery Validate and Form plugins to handle validation and submission.

I can successfully update profiles when the fields are technically correct, but can't figure out how to get feedback from the server if an error occurs after submission (aka invalid password, username already in use, etc).

Here's an example of my password update form:

      <form action="" class="secondary-content" method="post" accept-charset="UTF-8" id="pwForm">

Update password

    <fieldset>
      <input type="hidden" name="redirect" value="/profile">
      <input type="hidden" name="action" value="users/saveUser">
      <input type="hidden" name="userId" value="{{ user.id }}">
      <input type="hidden" name="password" value="{{ currentUser.password }}">

          New password Show password
          <input type="password" id="npw" name="newPassword" class="text-input" value="" required />

          <button class="button--red" type="submit">Update</button>

    </fieldset>
  </form>

Here is the javascript (in CoffeeScript syntax):

$('#pwForm').validate
  submitHandler: (form) ->
    $(form).ajaxSubmit
      type: 'POST'
      dataType: 'json'
      beforeSubmit: ->
        $(pwFields).transition opacity: 0
        $('#pwLoader').spin(opts).transition opacity: 1
      error: (xhr, status, error) ->
        $('#pwLoader').stop().transition opacity: 0
        $(pwFields).transition opacity: 1
        $(pwFields).append('There was an error. Please try again.')
      success: ->
        $('#pwLoader').stop().transition opacity: 0
        $(pwFields).text ''
        $(pwFields).html('
Password updated
').transition
          opacity: 1
          delay: 200

In this case, I'm actually tripping the "There was an error…" error no matter what I put in the field. If I pull out the javascript, the page refreshes and I don't get errors, but the password doesn't update.

I'm guessing it has to do with posting to the correct URL. Any ideas? Is it even worth using both/either of these plugins?

Thanks!

I myself am building a data locker using JavaScript to talk to Craft. How I have it set up is that the AJAX request is pointing to a template (which a request can be routed to without defining it in the Control Panel) that will load if there are errors. I can then redirect to a success template if I find no errors. Alternatively, you can set the location to redirect to like you did in your example. I'm returning JSON on both templates so that I can run client-side checks to see what I'm getting back.

So if I have errors, I check for those on my request url template and output the JSON if necessary. If I don't, I load my redirect template which either returns a success message or the data I'm looking to retrieve.

You can tell Craft that it's returning a JSON file by giving it a ".json" extension. Alternatively you can also set it manually with:

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

Either way, this should get you what you're looking to achieve.


Entry Tracker to see who has completed the course I'm working on a project using Craft CMS for the first time, so far so good, however i'm stumped on how to do the following:

Create a button on each entry in a structure that states you have read the follow article. When you click you have read the article, it reflects on your account page that you have read the follow article(s).

Hopefully this makes sense, but it's almost like a LMS, you learn about something on the page you click you have completed the stage then move on to the next stage.

Thanks!

I'd add an Entries field in your User field layout called Articles Read or such. Then whenever they click that they've read a particular article, I'd add the id of article entry that they've read to that field.

I'd do that probably via a custom plugin, but you could also do it with a simple form that passes the correct data to the the actionUrl('users/save-user') UsersController


Product Variant Detail Page I guess this is no big issue, but I'm pretty new to Craft Commerce :)
I'm trying to code a dynamic template for the product variants page.

This is the scenario: In the shop overview you see every product and all there variants. If you click on a variant image a detail page opens, showing you detailed information about this variant.

How can I access data of the variant (like title, description, asset) dynamically? Based on what the user clicked on?

I've already tried these two answers:

How do I select a specific product variant by element/field/entry?

Display image asset of a variant

The thing is, I can't use lineItem because the variant is not added to the cart yet. And I didn't manage to get the specific variant over getSegment and the url.

If I understand correctly you can check for available variants, then output whatever detail you need for the items. Something like this should get you started:

{# Check there are variants #}
{% if product.variants|length %}

  {# Loop through the variants #}
  {%- for purchasable in product.variants -%}

    {# Check the variant is available #}
    {% if purchasable.stock <= 0 and purchasable.unlimitedStock == false %}

      {{ purchasable.description }}
      {{ purchasable.salePrice|commerceCurrency(cart.currency) }}

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

  {% else %}
    {{ "Out of Stock"|t }}
  {% endif %}

{% endif %}

If you want to target only a specific variant you can refer to it directly using either its title (slug) or its variant ID, e.g.:

{% set variants = craft.commerce.variants.id(8376).first() %}

You can find more detail in the docs for the Variant Model and the docs for Craft Commerce Variants.


Robust Form Plugins for Craft? We're doing a rebrand and web overhaul for a Christian camp, retreat, and conference center. A big part of the site is a registration system where people can register for an event, fill out a detailed form with 30+ fields, then pay for registration. The forms will be pretty complex... people can do partial payments (via stripe), and each of the forms (10 or more) will be unique with conditional fields.  We're also hoping to hand off the form creation process to the client afterwards.

The only plugin I know that can handle something like this easily is GravityForms for WordPress, but I don't want to go the WP route. Is there anything like it out there for Craft? Or is Craft still too much in its infancy? Maybe a 3rd party form builder that will integrate nicely w/Craft?

Any help or guidance is appreciated!

Commerce is definitely Craft's achilles' heel right now.

Like you, I'd love to switch over completely off WP but picking the best tool for the job means either rolling up your sleeves and writing your own or picking the best available solution and unfortunately that could be WP/Gravity... at least right now.

  We're also hoping to hand off the form creation process to the client afterwards.

Not to go too far off the Craft path here, but from a client services perspective, this part scares the hell of me.

Forms tend to be tricky beasts to begin with—especially so when you add in the commerce part of it.
I don't know what your registration forms look like but I'm guessing a lot of them are going to be very similar. Do you actually need a form builder to put in name, address, etc. Or is the only thing that changes on the form the retreat date, lodging location, etc.

You can do a lot with Craft's custom fields and instead of building up a form like in Gravity or Ninja (like you might do in WP), bake in those fields that won't change in your template and just let the client change a few pieces from the back end—like the date, price, etc.—and compose the rest of the form with Twig and an action handler.

Regardless of whatever technology you pick, this kind of project tends to need ongoing support as well so if you can do it, get the client on some kind of monthly retainer; that'll remove a lot of the uncertainty as you move forward. Sometimes what clients say they need and what they actually end up needing is completely  different. Craft is going to grow as a platform too, so basically you're buying some time as the client grows with it. It's a nice sentiment to think you just "hand it off" but in my experience, it rarely works like that.


How do I add a second section name to this logic? I need to add a second section name to this code:

craft.entries.section('not homePage')

I can't figure out the correct formatting. I've tried:

craft.entries.section('not homePage,clientPage')
craft.entries.section('not homePage, not clientPage')

How do I add a second limiter?

A second limiter is added to the conditional like this:

craft.entries.section('and, not homepage, not clientPage')


Why is Craft storing so much temporary files inside the server tmp folder? For several websites (Craft CMS 2 & 3), servers ran out ot storage even if these websites were not storing a lot of assets.

After looking for why, I ended up in the temporary (tmp/) folder of these servers (which is at a lower level of these vhosts), where I found there were a lot of Craft-related filed that were not purged.

These are, for example:

Imagick files (some of them have a size of ~500 Mb!)
A lot of Twig PHP folders and files (which content looks very similar as found in /storage/runtime/)

Questions:

When and why these files are generated?
Why they are not automatilcally deleted?
When is it safe to delete them?

To be more specific:

Because I'm using Imgix, front-end image transforms are delegated to this remote service;
In this case, I think that only the CP uses Imagick;

Imagick uses the /tmp folder by default, but you can change it: https://github.com/ImageMagick/ImageMagick/issues/399#issuecomment-285793433


Craft CMS 3 Content Mover My database was corrupted after updating to 3.1.0 and no backup. Is there any script to move fields, sections and other staff to new fresh database?

Update
I found something like this scripts, but its not that one I needed

Depending on the level of "corruption", if the 3.1 Control Panel is still accessible and loading, you can use something like FeedMe to export the content you're looking for into a new Craft 3 install.


Any code fixes for "ini_set() has been disabled for security reasons" I have two clients using Craft and their hosts will not allow ini_set as they have it as a disabled function in the global php.ini.  I also can't enable in througth a custom php.ini.  Is there any way to modify Craft to get past the ini_set issues?  I have the site all setup, the pages work locally, when I upload to the server we just see a blank page.

Any advice is appreciated as they both do not want to change hosts.

Thanks.

Well, the code fix is to put an @ sign before every call to ini_set that Craft makes and all of Craft's dependencies in craft/app/vendor suppressing the error message @ini_set().

But I definitely wouldn't recommend that as you'll have to maintain some 40+ hacks across nearly as many files that could get blown away during any auto-update.


Assign entry id to title with entry form I have an entry form to take user generated content.

The section it passes the info to has a customised title format Submission ID: {id}

However, when the entry gets submitted, the title in the CP (and indeed in the templates) just show as Submission ID:

It's not until the entry is re-saved at the control panel level (although I haven't tried a front end edit form) that the appropriate id shows e.g. Submission ID: 12465

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

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

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


Adding cache headers to Nginx configuation file breaks the /admin area When I add this to my Nginx Confirguration file:

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires 7d;
    add_header Pragma "public";
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}

In the admin area I get all 404 responses on those assets (js, css, png, etc).

Without that in my configuration, for example, settings.css is OK:

Request URL:http://{site}admin/resources/css/settings.css?d=1411426522
Request Method:GET
Status Code:200 OK
Cache-Control:max-age=31536000
Connection:keep-alive
Expires:Sun, 11 Oct 2015 02:25:24 GMT
Last-Modified:Mon, 22 Sep 2014 22:55:22 GMT
Pragma:cache

And then with the code, the settings.css is 404 Not Found

Request URL:http://{site}/admin/resources/css/settings.css?d=1411426522
Request Method:GET
Status Code:404 Not Found
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Expires:Sat, 04 Oct 2014 02:31:56 GMT
Pragma:no-cache

Craft rewrites the location of those files using a query string, which is what's causing nginx to lose track of them. Using the try_files directive should force nginx to find and serve them properly.

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
  try_files $uri /index.php?$query_string;
  expires 7d;
  add_header Pragma "public";
  add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}


Apple.com style Localization Its it possible to use the localization feature to create regional site versions.

Currently when I attempt to use this feature I can only view pages in my locale.

The Apple.com website shows a great example of what we're trying to achieve.

http://www.apple.com/au/
http://www.apple.com/nz/
http://www.apple.com/uk/

We'd like to create new entries and have a draft appear in all regional sub directories.

E.g.

http://www.acme.com/nz/news/news-release
http://www.acme.com/au/news/news-release
http://www.acme.com/uk/news/news-release

...

The main point is we want the entire site open to users from anywhere.

We're not yet concerned with translations either.

I had some helpful advice via Craft's support channels. Here was the solution I arrived at with their assistance:

You can hard code the locale in index.php in the doc root.

define('CRAFT_LOCALE', $locale);

The normal approach seems to be that multiple index.php pages can be used in a multi-locale site. I prefered to keep the one, so I used this tiny hack that derives from the url what the desired locale is:

<?php

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

$url_folder = substr(substr($_SERVER["REQUEST_URI"],1), 0,
    strpos(substr($_SERVER["REQUEST_URI"],1), "/"));
$locale = 'en_nz';

if($url_folder === 'worldwide') {
    $locale = 'en_zz';
}
else {
    $locale = 'en_' . $url_folder;
}

define('CRAFT_LOCALE', $locale);

This hack is confined to the index.php so it seems pretty clean.


htaccess non-www rewrite showing index.php in URL I am using htaccess to rewrite any www url to a non-www version

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

When I type domain.com/about it works fine, however when I type www.domain.com/about it changes the URL to domain.com/index.php?p=about

I have 'omitScriptNameInUrls' => true, enabled.
I also have this in my .htaccess file

RewriteEngine On

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]

What am I doing wrong here?

Edit:
Here is the the vhost file.

<VirtualHost *:80>
    ServerName domain.com
    ServerAdmin webmaster@domain.com
    DocumentRoot /var/www/

    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Check out the official Apache documentation on Canonical domain rewrites: https://httpd.apache.org/docs/2.4/rewrite/remapping.html#canonicalhost


Sprout Import Doesn't Recognize Asset folderPath Property I'm trying to import entries with an Asset inside a subfolder. Since I don't know what the new Craft subfolder ID will be for each Asset I tried to use the folderPath property from Craft's Asset element class:

[
{
    "@model": "barrelstrength\\sproutimport\\importers\\elements\\Entry",
    "attributes": {
        "sectionId": 2,
        "typeId": 2,
        "authorId": 1,
        "slug": "my-sample-document",
        "postDate": "2017-11-09 13:06:00",
        "expiryDate": null,
        "enabled": true
    },
    "content": {
        "title": "My Sample Document",
        "fields": {
            "description": "
Nulla sit amet est. In hac habitasse platea dictumst. Pellentesque ut neque.
"
        },
        "related": {
            "documentFile": {
                "@model": "barrelstrength\\sproutimport\\importers\\elements\\Asset",
                "params": {
                    "filename": ["my-sample-document.pdf"],
                    "volumeId": 9,
                    "folderPath": "documents/pdfs/"
                }
            }
        }
    }
}
]

However the import fails with this error:

  [error][sprout-import] Setting unknown property: craft\elements\db\AssetQuery::folderPath

I don't get an error when I use the folderId property. Can I only use properties that correspond with database columns? Is there any way to do this if I don't know the subfolder ID for every asset I'm importing?

Craft 3.0.26.1
Sprout Import 1.0.0-beta.14

folderPath is not supported when relating an asset to an Entry but there is a workaround. In your generation script you can call the code below to get the folderId with the given path:

$folderId = \craft\records\VolumeFolder::find()
->where(['path' => 'documents/pdfs/'])
->scalar();


How to create subfolders for entries? I am very new to Craft CMS and just testing out the CMS. In our old system we had 2 levels of virtual folders and I need to keep that structure. I don't see anything that would correspond to that in Craft. Is there anything that would let me create 2 levels of folders?

If you use make your section a Structure, it will allow a hierarchy of entries.

See the docs on section types to learn more about the different types of sections in Craft.


What does the 'modifyEntrySources' hook do? What does the modifyEntrySources hook do exactly, and when might one use it? Can someone help clarify this please?

"Source" is in the context of "where an element is pulling its data from".

The easiest example is with Assets, because they have easily defined Asset Sources settings portion of the control panel, but all elements (entries, tags, categories, users, etc.) have sources behind the scenes.

See the CategorySources plugin for an example of how it might be used (including a screenshot).


Load correct language Ajax I'm having a problem with my ajax-loading when I'm on the english version of my page (My main language is Norwegian). I have a file named loadmore.html that I'm loading in on index.html when pressing a button. The problem is that this page won't show me the English version when I'm on the english version of the site. I really appreciate all your help. There's my code:

$('.showmemore_inner h2').on("click", function(e){
    $('.third_article_module').load('/loadmore.html');
    $('h2.lasterinn').css('display', 'block');
    return false;
    e.preventDefault();
});

Loadmore.html:

        {% for entry in craft.entries.section('artikkel').order('dateCreated desc') %}

            {% for block in entry.bildekarusell.limit(1) %}
                {% if block.type == "bilde" %}

                        {% for image in block.bilde %}

                            <picture>

                                <source srcset="{{ image.getUrl('hovedsideSekscolBilde') }}" media="(min-width: 990px)">
                                <source srcset="{{ image.getUrl('hovedsideSekscolBilde2') }}" media="(max-width: 990px) and (min-width: 625px)">

                            </picture>

                        {% endfor %}

                {% endif %}
            {% endfor %}

                    {% for category in entry.kategorier %}
                        {{ category.title }}
                    {% endfor %}

{{ entry.title }}

{{ entry.postDate|date("M Y") }}

    {% endfor %}

UPDATE: I tried this code in my _layout.html file but it's not working:

One issue may be that your javascript is requesting a specific url as defined from the site root, thus not giving craft the opportunity to do it's locale routing magic (keep in mind the url for languages other than the default locale may actually be '/no/loadmore.html' — or however you have defined the locale routes in your config settings). So just changing the request url in javascript may solve the problem.

$('.third_article_module').load('loadmore');

Another thing to keep in mind in general is that you can always specify a locale as part of the query, if you ever need to bypass or override craft's locale routing for some reason.

{% set locale = craft.i18n.getCurrentLocale() %}
{% set entries = craft.entries.section('artikkel').locale(locale).order('dateCreated desc') %}
{% for entry in entries %}
    ...
{% endfor %}

Another thing worth mentioning is that you could potentially also ajax load content from the current page template by using an isAjax conditional, thus eliminating the need for a separate 'loadmore' template altogether.

{% if not craft.request.isAjax %}
    {# render page content #}
{% endif %}

{% if craft.request.isAjax %}
    {# render loadmore content #}
{% endif %}

You can then just pass the entry url to your javascript and ajax load the current page (in this case I'm passing the url by defining a 'data-url' attribute on the .showmemore_inner h2 dom element; i.e. <h2 data-url="{{ entry.url }}">).

$('.showmemore_inner h2').on("click", function(e){
    e.preventDefault();
    var url = $(this).attr('data-url');
    $('.third_article_module').load(url);
    $('h2.lasterinn').css('display', 'block');
});

Note: also e.preventDefault() should come before any return statement or else it will never get a chance to fire.


Add fields to image popup Is it possible to add additional fields to the image popup in redactor? In addition to Title, Caption and Link.

I don't think there is a way without hacking Redactor or adding a custom Redactor plugin that mimics/extends the existing Image/Link button functionality.


Accessing entries in a matrix field in plugin I am writing a plugin function that takes an entry id, the entry has a matrix field (called block) and the matrix has a blocktype which contains a number field (blockStep), an entries field (blockContent) and another entries field (blockDependency).

I am getting the entry, which i am calling a module, like this:

$module = craft()->entries->getEntryById($moduleid);

This works fine. Then I get the matrix field, called block, like this:

$matrixBlocks = $module->block;

This also works fine. However, when I try to loop through the matrix field, like this:

    foreach ($matrixBlocks as $block){
      var_dump( $block->getContent()->blockStep);
      var_dump( $block->getContent()->blockContent);
      var_dump( $block->getContent()->blockDependency);
    }

Only the blockStep, which is a number, is set - the two entries fields are just returning NULL.

Can someone help? How should I be accessing these entries fields?

Thank you.

I think I've figured out how to do this now (mainly through trial and error).
The code above should actually be like this:

foreach ($matrixBlocks as $block) {

    foreach ($block->blockContent as $blockContent) {
        ....
    }
    foreach ($block->blockDependency as $blockDependency){
        ....
    }
}

And the the $blockContent and $blockDependency variables will contain the entries required.


Using Craft to render frontend pages in addition to using it headless I’m looking to create a craft site for some digital storytelling pieces. The pages will be curated by various people within my team. But I also like the idea of using the CMS to push separate content within the cms, to things other than the website. This would give us a lot of flexibility. Can you use Craft to render the front pages using twig as normal, and additionally run it in headless mode? Or if i want the benefit of using it as a headless CMS would I instead have to render the frontend site using a static site generator, like Gatsbyjs? What are my options if I want to use it both ways?

Thanks,

Richard

Absolutely! Craft works really well like this. You can use twig to render your website, then either element api or graph QL (built in to craft 3.3) to open up your data to other applications.

I run several sites like this where I’ve opened up various parts of the content for external use, e.g. the news feed for use in an app.


Is there a template conditional to determine whether a plugin is installed? Let's say I've got a hot plugin called Cornballer, and I'd like to avoid embarrassing template errors if I refer to it in a template without yet installing it.

I'd like to get away with this...

 {% if craft.cornballer %}

 {{ craft.cornballer.simulate('little') }}

 {% endif %}

...so that any cornballing is simply ignored and no errors result. But Craft allows no such thing:

  Method "cornballer" for object "Craft\CraftVariable" does not exist

Is there a way?

This should do it:

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


Method for creating Category Group landing pages I have a selection of category groups as follows:

Suitability
Colour
Finish
etc

They all have many categories within them. I have set up some routes for /suitability etc to show the user a /shop/category.twig template for the category group landing pages.

But my issue I'm having is getting the context of the page based on the slug.

I have read a very old SE post that kind of offers a solution, but it's only useful for getting the name. I need to build on this to get the group. But it doesn't look like there's a way to 'get' a category group.

I may be wrong and missed something but I've only found ways to obtain category group info based on context of a category itself as follows:

{# get the category group slug #}
{% set slug = craft.app.request.segment(1) %}

{# get the first category within this group and output the groups' name #}
{% set catGroupName = craft.categories.group(slug).first.group %}

Any advice on a much neater way to obtain a category group would be handy. Thanks

2nd Revision:

The category group field layout is for categories within that group. Categories groups do not have fields assigned to them, only to the categories within a group.

1st Revision:

To get the fields of a category group, set the category like so:

{% set group = craft.categories.group('suitability').one() %}

And use fields:

{{ group.someFieldHandle }}

Original Answer:

To retrieve the category:

{% set slug = craft.app.request.segment(1) %}
{% set category = craft.categories.group('suitability').slug(slug).one() %}

Then use its fields or related:

{{ category.title }}
{{ category.somePlainTextField }}
{% set entries = craft.entries.relatedTo(category).all() %}

It would be better to set the template for the category on the category group settings page.

Set the URI to /suitability/{{ slug }} and the template to /shop/category.twig
Then you can just use the category in the template without having to set it by getting slug and pulling the category from the group. Also, this allows you to point multiple category groups to the same template if their template will be similar.


Call function from plugin in template In craft 2 I had a simple plugin that I used to run some php code. I could call the function like this.

{{ craft.pluginname.functionname }}

However I have been unable to do the same thing in craft 3. I have created a new plugin for craft 3. Moved my functions to the main plugin file in src.

Is there a new way to call a function from a plugin in craft 3?

Ok got it figured out.

author below = root plugin path in vendor folder

In main plugin file had to add

use author\pluginname\variables\variablename;
use craft\web\twig\variables\CraftVariable;

Updated init event to

Event::on(
    CraftVariable::class,
    CraftVariable::EVENT_INIT,
    function (Event $event) {
        /** @var CraftVariable $variable */
        $variable = $event->sender;
        $variable->set('pluginname', variablename::class);
    }
);

Created variables file in variables folder src/variables/variablename.php

namespace author\pluginname\variables;
use author\pluginname\mainClassName;
use Craft;

class variablename
{
    //Custom Functions Here
    public function test() {
        echo 'Test';
    }
}

Then from a template I was able to use

{{ craft.pluginname.test }}

You'll need to register your variable in your plugin's init() method, like this:

Event::on(
    CraftVariable::class,
    CraftVariable::EVENT_INIT,
    function (Event $event) {
        /** @var CraftVariable $variable */
        $variable = $event->sender;
        $variable->set('pluginname', PluginVariable::class);
    }
);

c.f.: https://docs.craftcms.com/v3/extend/extending-twig.html


Email Before Membership / Subscription Renews via Charge / Stripe? I've got a client requesting that their subscribers get an email notification before their membership is renewed (via Stripe / Charge).

Having glanced over Stripe's documentation, it doesn't look like there's a webhook to handle this, nor does it look like something that Charge supports out of the box.

Is there a solution out there more straightforward than rolling my own plugin (which I haven't done before, but am certainly willing to attempt)?

Developer of Charge here.

While it's not a feature that's currently supported out the box with Charge, it is something that's on the FR list, and is something I'm looking at adding.

If you drop me a line directly I can talk over some of the options with you.


Can't get correct template for ajax call Background: I've inherited a site built in craft that has a page called "updates" with a button to load additional entries through ajax. The updates page is an entry in the "page" structure and when it's template is called it loads entries stored in a channel also called "updates". The template the "pages" structure points to is pages/_entry.html, and this holds the logic for gathering entries stored in the "updates" channel. However, the ajax script calls /updates/q?param=1 which is somehow calling the template updates/index.html. All while the channel is set to call template entries/_entry.html for the individual entries in the channel.

So I tried to create a blog page that would work the same way. I created an entry in the "pages" structure called blog, then created the template blog/index.html which is the same as updates/index.html. The ajax script calls /blog/q?param=1 but it returns a 404. I even created a channel in the cms called blog wondering if that was the case but it hasn't helped. What does the url need to be to return blog/index.html?

pages/_entry.html

{% extends "_layout" %}
{% block content %}
{% set myJs %}
window.entryType = '{{ entry.type }}';
{% endset %}

{% includeJs myJs %}
{% cache unless craft.config.devMode %}

  {% if entry.type != 'contact' %}
    {% include ['_partials/_page-header-' ~ entry.type, '_partials/_page-header'] %}
  {% endif %}

  {% include ['_partials/_page-content-' ~ entry.type, '_partials/_page-content' ] %}

{% endcache %}
{% endblock %}

updates/index.html

{% if craft.request.isAjax %}
  {% set layout = "_ajax" %}
{% else %}
  {% set layout = "_layout" %}
{% endif %}

{% extends layout %}
{% set title = 'Updates' %}
{% block content %}

{% cache for 3 hours unless craft.config.devMode %}
  {% if craft.request.isAjax %}
    {% include '_partials/_get-updates' %}
  {% else %}
    {% set entry = craft.entries.slug('updates').featuredUpdate %}

        {% include '_partials/_updates-filter' %}
        {% include '_partials/_grid-cards' %}

          Load More

  {% endif %}

{% endcache %}
{% endblock %}

It looks like a custom route has been set up for /updates/q which points to the updates/index.html template.

There are two places this could have been configured:

Dynamic routes set up in the control panel, or
Advanced routing set up in the routes.php file.

Look in both of those places to see if a custom route has been set up for /updates/q. If so, you will need to set up a similar one for /blog/q so that Craft knows which template to render for those requests.

Craft's routing docs are a good place to start to understand how all of this works.


FeedMe Node Attributes I have the following XML:

<nodes>
    <node>
        <title>Test Org - Pleae Ignore</title>
        <logo>
            <enclosure url="https://www.mydomain.org/sites/default/files/louis%20xiv.jpg" length="71280" type="image/jpeg" />
        </logo>
    </node>
    <node>
        <title>Test Org - Pleae Ignore</title>
        <logo>
            <enclosure url="https://www.mydomain.org/sites/default/files/louis%20xiv.jpg" length="71280" type="image/jpeg" />
        </logo>
    </node>
    <node>
        <title>Test Org - Pleae Ignore</title>
        <logo>
            <enclosure url="https://www.mydomain.org/sites/default/files/louis%20xiv.jpg" length="71280" type="image/jpeg" />
        </logo>
    </node>
</nodes>

And the following template markup:

{% set params = {
    url: 'https://www.domain.org/xml-details?nid=12345',
    type: 'xml',
    element: 'node',
    cache: 60,
} %}

{% set feed = craft.feedme.feed(params) %}
{% for node in feed %}
    {{ node.title }}
    {{ node.logo.enclosure.attributes.url }}
{% endear %}

{{ node.title }} displays fine, but {{ node.logo.enclosure.attributes.url }} displays nothing.

Based on other threads I've read, I've also tried {{ node.logo.enclosure['@url'] }}

Neither returns the value of the url attribute.

Any help getting this to work is appreciated.

EDIT: Using just {{ node.logo }} in the template outputs <enclosure url="https://www.mydomain.org/sites/default/files/louis%20xiv.jpg" length="71280" type="image/jpeg" />.

EDIT: Here's my {{ dump(node) }} output.

array(30) {
  ["recordId"]=>
  string(5) "19795"
  ["title"]=>
  string(22) "Robertson Blood Center"
  ["summary"]=>
  string(101) "
Volunteer- Donate blood. Your donation of life is used by wounded military at home and abroad.
"
  ["logo"]=>
  string(156) "<enclosure url="https://www.mydomain.org/sites/default/files/1959440_10152076927213038_3915913252856478361_n%5B1%5D_2.jpg" length="35608" type="image/jpeg" />"
}

I believe the correct syntax you're looking for is:

{{ node.logo.enclosure['@url'] }}

As a handy hint, you can use the following to inspect any element parsed by Feed Me to see how you can access it. Using {{ dump(node.logo.enclosure) }} for example, you can see an array with keys and values for you to access.

This is also outlined in the documentation - https://verbb.io/craft-plugins/feed-me/docs/feature-tour/using-in-your-templates#example-template-code

EDIT: Refer to full code below

{% set params = {
    url: 'http://feedme.craft.dev/stack.xml',
    type: 'xml',
    element: 'node',
} %}

{% for node in craft.feedme.feed(params) %}
    <pre>
        {{ dump(node) }}
    </pre>
{% endfor %}

Produces:

array(2) {
  ["title"]=>
  string(23) "Test Org - Pleae Ignore"
  ["logo"]=>
  array(1) {
    ["enclosure"]=>
    array(3) {
      ["@url"]=>
      string(60) "https://www.mydomain.org/sites/default/files/louis%20xiv.jpg"
      ["@length"]=>
      string(5) "71280"
      ["@type"]=>
      string(10) "image/jpeg"
    }
  }
}

EDIT 2: Looking at your exact feed, I can see the issue. Your feed actually has HTML, which is interpreted as a string. For instance:

<logo>
    &lt;enclosure url="https://www.mydomain.com/1959440_10152076927213038_3915913252856478361_n%5B1%5D_2.jpg" length="35608" type="image/jpeg" /&gt;
</logo>

Notice how is your original example its assumed its all XML? In fact, the logo node contains HTML, which is just treated like a string.


Service Mark in title Anyone have an idea on how to incorporate a service mark (SM) into the title of an entry? I've tried just doing SM, tried the code for SM & # 8 4 8 0 ; (without the spaces), and nothing works. I even tried creating a new rich text field so I could do it there and have a conditional to show that field instead of the title field, but that makes it so that it can't be used in different headline tags on different pages, as its auto-enclosed into a pargraph or h3 or whatever.

Any thoughts or ideas are greatly appreciated!!

I think the issue is that craft will sanitise (escape) any code before it goes into the database, to prevent any code injection and twig will also do the same at a template level (to prevent script injection).

If you have your entry title as DIVA! Becomes Famous &#8480 for example, it will appear like that in craft and in your templates, but if you do {{ entry.title|raw }} it will actually output ℠ in your template.

From the twig docs:

  The raw filter marks the value as being "safe", which means that in an environment with automatic escaping enabled this variable will not be escaped if raw is the last filter applied to it

See more in twig docs


Authentication by a custom field I added a field called "phonenumber" to the user profile fields which I want to use for login purposes, too.

Usually Craft allows an authentication by username or email-address. Is there a way to add another field for authentication, e.g. the custom field phonenumber? The goal is to expand Craft to accept logins via username and email-address as well as the phonenumber.

The short answer is no. Craft does not natively support this, and there's no way to implement it via a hook (or event).

A quick browse through the code shows that the UserIdentity::authenticate method is where most of the action takes place (called from the UserSessionService::login method), and that's very much tied to using either a username or an email address.

Your only option is to implement a custom plugin, with its own controller endpoints, which handles login requests. You would then submit the login form to your plugin, rather than to Craft.

Such a plugin will, of course, need to follow all of the same security best practises as the current Craft "login" implementation, and be actively maintained in case any vulnerabilities come to light.


Display selected radio's value The issue arises from inline three buttons (Viewer, Video, Photo) via CSS.

The idea was to make the buttons more responsive for example if I want to display just one button than stretch to 100% width within the parent. Two buttons (50% each) and three buttons (33.33% each).

I guess if I setup radio field and the values are displayOne, displayTwo and displayThree.

{% for option in entry.viewerOption %}

{% if option in entry.viewerOption.value.selected(displayOne) %}
Viewer
{% else %}
Photo
{% else %}
Video
{% endif %}

{% else %}

{% if option in entry.viewerOption.value.selected(displayTwo) %}
Viewer
Photo
Video
{% endif %}

{% else %}

{% if option in entry.viewerOption.value.selected(displayThree) %}
Viewer
Photo
Video
{% endif %}
{% endfor %}

I am not sure what is the best method to dynamically single, duel or triple buttons base on selected radio value.

I'm not sure I totally get what you're trying to do, but if you want to cut down a bit of the code duplication in here a good start would be to use a Twig macro.

So you'd set up your macro like this:

{% macro input(cssClass) %}
    Viewer
    Photo
    Video
{% endmacro %}

{% from _self import input %}

Then you'd call it like this:

{{ input('dual') }}

If you don't need the value of the radio buttons for anything else, you could always give them the value of your CSS class; that way you don't need to convert them from one thing to another. If you did it this way then you could just call your macro like this:

{% set cssClass = entry.viewerOption %}
{{ input(cssClass) }}

Make sure you've set a default option for your radio button when you've added it in the Control Panel.


Save as a new entry doesn't seem to copy all locales I have a website with 2 locales set up, and have an entry that has content in both.

When I Save as a new entry, Craft only saves the locale that is open at the time, and then copies that same content to the other locale, instead of copying the original localised content.

So I end up having one entry with the same content on both locales, instead of having an exact copy of the previous entry (with different content in the 2 locales)

Is this a bug, a normal behaviour or am I doing something wrong?

This is a known Craft 2 issue that has been fixed in the upcoming Craft 3 release.

It likely won't be back-ported to Craft 2 since it takes advantage of much larger refactorings.


Same shipping rule name in different methods not allowed? We are setting up shipping methods and rules as follows:

Methods: FedEx Standard, FedEx Priority, FedEx Overnight

For each method we wanted to add the following rules: US, Canada, International

However, when trying to add another rule for another Shipping Method, we get this error:

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'Canada' for key 'craft_commerce_shippingrules_name_unq_idx'

I assume we cannot have duplicate rule names across different methods? If so, this seems odd. Of course we can make each rule have a unique name (ex. US Standard, US Prioriy, etc) but it seems like unnecessary complication. Is that our only option?

Confirmed by Luke this was due to a bug to be fixed in the next release of Commerce.


retrieve matrix data to twig file I create a section clientSection which I linked an matrix field like in this image:

The field has two block types : clientImage which has an field clientImage and clientDescription which has an field with same name.
I want to output in twig file but I don't know how exactly

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

{% for client in clients %}
  {# display content here #}
{% endfor %}

Thank's

You will need to use your Matrix field handle (which you didn't show in your question) and replace yourMatrixFieldHandle:

{% for client in clients %}
    {{ client.title }}

    {# Get all blocks related to the client entry #}
    {% for block in client.yourMatrixFieldHandle.all() %}

        {% switch block.type %}

            {% case "clientImage" %}

                {% for image in block.clientImage.all() %}
                    <img src="{{ image.getUrl() }}" alt="{{ image.title }}">
                {% endfor %}

            {% case "clientDescription" %}

                {{ block.clientDescription }}

        {% endswitch %}

    {% endfor %}

{% endfor %}

Read more about working with Matrix fields here


How to update Craft CMS/plugins without downtime? On our production server, we have strict SLAs concerning when our site can be down.  I've noticed that when I update Craft CMS 3 (using "./craft update all" on the server), the site will go down for anywhere from 1-30 seconds.  Once the update is completed, everything returns to working.  Has anyone seen this before?  How can I update Craft without downtime?

I think the best solution would be to integrate a CI with "Zero downtime deployment".

You may have a look at this article:
https://craftquest.io/articles/what-are-zero-downtime-atomic-deployments

Or have a look at this deploy plugin:
https://github.com/elfacht/craft-deploy

Or just google for "zero downtime deployment".


How can I escape Twig code to prevent it from being parsed? How do I escape Twig code to prevent it from being processed?

Escape single lines as strings:

{{ '{% set foo = "bar" %}' }}

Use autoescape to escape multiple lines, optionally specifying a syntax (see docs):

{% autoescape %}
     {% if foo != "bar" %}
         {% set foo = "bar" %}
     {% endif %}
{% endautoescape %}

Use verbatim to treat multiple lines as raw text:

{% verbatim %}
     {% if foo != "bar" %}
         {% set foo = "bar" %}
     {% endif %}
{% endverbatim %}


Prevent redirecting to the control panel from a URI of "/login" when logged in I have a top level page that needs the URL of "/login/". It has nothing to do with an actual Craft login.

If I have a logged-in session, that url redirects me to the dashboard (via UsersController->actionLogin).

If I'm logged out, the page renders fine.

I thought setting craft.config.loginPath to something other than "login" would fix it, but it didn't seem to have an effect.

I can confirm this is a bug in the latest build of Craft (2.1.2570).  The fix for this will be in Tuesday's (09/02/2014) release.

UPDATE

This bug has been fixed in Craft 2.2. http://buildwithcraft.com/updates#build2579


Is it possible to return a User Model Entry or userid from a successful registration form submission? Is there a way to return a user model entry, userid, or some other identifier (and/or variables in general) from a successful registration form submission using the hidden redirect parameter?

In the docs for action/saveUser I see some mention of {id} in the redirect string, but I'm not exactly sure sure how this works (or if it's even related).

      if (isset($_POST['redirect']) && mb_strpos($_POST['redirect'], '{userId}') !== false)
      {
           craft()->deprecator->log('UsersController::saveUser():userId_redirect', 'The {userId} token within the ‘redirect’ param on users/saveUser requests has been deprecated. Use {id} instead.');
           $_POST['redirect'] = str_replace('{userId}', '{id}', $_POST['redirect']);
      }

The reason I ask is that I am creating a multipart form that relies on the values of the previous form submission to continue (starting with user account registration). I essentially want to redirect back to the form, fill out the next part, submit, redirect back to form, fill out next, etc. (controlling the workflow with javascript or twig). FYI, using impersonate() will not work for me in this case, because user must be admin, or in a custom 'manager' group.

As a side question, I also see craft()->userSession->setNotice(Craft::t('User saved.')); used throughout the saveUser controller. Is there a corresponding getNotices() similar to getErrors() or some way to retrieve these on the front-end?

In your redirect hidden input in your form, add an {id} tag like so:

<input type="hidden" name="redirect" value="nextStep/{id}">

And that will be populated with the newly created user's userId.

  Is there a corresponding getNotices() similar to getErrors() or some way to retrieve these on the front-end?

You'd have to duplicate the code that the control panel uses to retrieve the notices on the front-end of the site.


File upload fails without error I try to upload a file larger than the 16 MB Craft limit. The file I try to upload is 61 MB.

I have set the maxUploadFileSize to 256000000.
My hosting company changes the server PhP settings to this:

max_file_uploads = 20
upload_max_filesize = 256M
max_input_time = 180
memory_limit = 256M
post_max_size = 256M

The file starts to upload but when the progress bar is at 50%, it just stops. It keeps "uploading" (wheel keeps spinning in the top right corner) but nothing happens anymore.

I don't get a front-end error either. But in my browser console it says: ERR_CONNECTION_RESET

Anyone who can help me find a solution?

UPDATE

So, my hosting company made the time-out longer and the error dissapeared.
But I still can't upload the file as I get this error in the console window now:

POST http://krycer.be/index.php/admin/actions/assets/uploadFile 502 (Proxy Error ( The specified network name is no longer available.  ))

When I diasble my proxy I get this error:

POST http://krycer.be/index.php/admin/actions/assets/uploadFile 500 (( The specified network name is no longer available.  ))

The file upload completes, but the status bar remains visible, allthough full, and the file is not visible in the assets folder.

It would be worth checking craft/storage/runtime/logs/craft.log, it's very likely there's a clue in there.


Slightly-slow page load for blank page Just wanted to check in to see if what i'm seeing is reasonable. Just trying to tweak the performance of a single-page Craft site, and basically working backwards to find bottlenecks. Following all the suggested items (devMode off, static assets caching, minimise db calls, etc).

However, working my way all the way back to a blank template file (no code at all), no plugins enabled, the page still take 250-300ms to load nothing at all. All this while running locally via MAMP.

Is this an expected speed? I'm aware thats pretty fast, but would've thought locally would be near instantaneous. This will only get worse on a server (especially shared hosting).

MAMP isn't really tuned for performance either. And also keep in mind Time to First Byte is not the only indicator of a fast website. You should consider overall perceived time and actual download time as factors as well.

CloudFlare talked about one aspect of this on their blog... for example: with Gzip compression, the web server has to wait while it compresses the output then send it along. That adds to your TTFB. So on first blush, gzip compression would appear to be a bad thing but in reality, your overall download time and file size shrink, and as a result, it's an easy win.

If your content doesn't change all that much, when you get your Craft site up live, you might also want to consider caching on the server level as well, either with Nginx (fastcgi_cache) or something like Varnish in front of Apache. Those layers add complexity (e.g. when and how to clear the cache?) but it'll get you super fast output if that's your goal.


error when trying to loop through grouped entries according to dropdown field I was trying to follow this example from stack overflow to loop through a list of entries and output them by a custom dropdown field

{% set allEntries = craft.entries.section('resource').find() %}
{% set allEntriesByCat = allEntries|group('entry.resourceType') %}
{% for cat, entriesInCat in allEntriesByCat %}

{{cat}}

    {% for entry in entriesInCat %}

{{entry.title}}

{{entry.resourceContent}}

    {% endfor %}
{% endfor %}

But if I do that, I get the error: Internal Server Error
Craft\EntryModel and its behaviors do not have a method or closure named "entry".

You have to remove the entry from your entry.resourceType

{% set allEntriesByCat = allEntries|group('resourceType') %}

will work


Separate time settings from user locale? I would like to render the DateTime fields in the backend with european time format, even though the user I'm logged in with is set to English/US.

Is this possible?

No, there's currently no setting to choose your preferred date and time format. What you can do though, is to hack your craft/app/framework/i18n/data/en_us.php

'dateFormats' => array (
    'full' => 'EEEE, d. MMMM y',
    'long' => 'd. MMMM y',
    'medium' => 'dd.MM.y',
    'short' => 'dd.MM.yy',
),
'timeFormats' => array (
    'full' => 'HH:mm:ss zzzz',
    'long' => 'HH:mm:ss z',
    'medium' => 'HH:mm:ss',
    'short' => 'HH:mm',
),