How can I conditionally resave entries based on the value of an entry's field in a Craft 3 Module/Plugin? Scenario: I want to programatically bulk resave entries in a certain Site in a certain Section of a certain Type.

I have a Craft 3 Module with a Console Controller containing following code:

public function actionResaveEntries()
{
    $site = Craft::$app->sites->getSiteById(self::SITE_ID);
    $section = Craft::$app->sections->getSectionById(self::SECTION_ID);
    $entryType = Craft::$app->sections->getEntryTypeById(self::ENTRY_TYPE_ID);

    Craft::$app->getQueue()->push(new ResaveElements([
        'description' => Craft::t('app', 'Resaving {section}, {type} entries', [
            'section' => $section, 'type' => $entryType->name,
        ]),
        'elementType' => Entry::class,
        'criteria' => [
            'siteId' => $site->id,
            'sectionId' => $section->id,
            'typeId' => $entryType->id,
            'status' => null,
            'enabledForSite' => true
        ]
    ]));

    $result = 'something';
    echo "Resaving entries\n";
    return $result;
}

This works as expected when running ./craft resave-entries-module/resave-entries/resave-entries from the command line & also via a cron job.

However, I now want to modify my code to run Craft::$app->getQueue()->push(new ResaveElements() only under certain conditions. Specifically, when a deadline (custom date/time field in entry type) has passed.

I tried following, but it doesn't run at all regardless if before or after deadline date. The conditional seems to be ignored.

public function actionResaveEntries()
{
    $site = Craft::$app->sites->getSiteById(self::SITE_ID);
    $section = Craft::$app->sections->getSectionById(self::SECTION_ID);
    $entryType = Craft::$app->sections->getEntryTypeById(self::ENTRY_TYPE_ID);

    $entries = Entry::find()
        ->siteId(self::SITE_ID)
        ->sectionId(self::SECTION_ID)
        ->typeId(self::COMP_ENTRY_TYPE_ID)
        ->all();

    foreach ($entries as $entry) {
        // Set deadline
        $deadline = $entry->competitionJudgingEnd;
        // Check if after deadline
        $now = new DateTime();
        if ($now > $deadline) {
            Craft::$app->getQueue()->push(new ResaveElements([
                'description' => Craft::t('app', 'Resaving {section}, {type} entries', [
                    'section' => $section, 'type' => $entryType->name,
                ]),
                'elementType' => Entry::class,
                'criteria' => [
                    'siteId' => $site->id,
                    'sectionId' => $section->id,
                    'typeId' => $entryType->id,
                    'status' => null,
                    'enabledForSite' => true
                ]
            ]));

            //$result = 'something';
            echo "Resaving entries\n";
            //return $result;
        } else {
            //$result = 'nothing';
            echo "Not resaving entries\n";
            //return $result;
        }
    }

In an effort to troubleshoot, I changed the conditional to if ($entry->title == "A known title"), but it also seems to be ignored. I.e. resave not occurring.

What am I doing wrong, and what can I do to get this working?

UPDATE 01: The conditionals are actually working. There are 3 entries that meet criteria in $entries = Entry::find(). However, the loop seems to be stop at the first entry. This entry changes if I change the criteria.

UPDATE 02: It looks like the return $result; was breaking the loop. Updated code above by commenting out return statements.

My working solution:

public function actionResaveEntries()
{
    $site = Craft::$app->sites->getSiteById(self::SITE_ID);
    $section = Craft::$app->sections->getSectionById(self::SECTION_ID);
    $entryType = Craft::$app->sections->getEntryTypeById(self::ENTRY_TYPE_ID);

    $entries = Entry::find()
        ->siteId(self::SITE_ID)
        ->sectionId(self::SECTION_ID)
        ->typeId(self::COMP_ENTRY_TYPE_ID)
        ->all();

    foreach ($entries as $entry) {
        // Set deadline
        $deadline = $entry->competitionJudgingEnd;
        // Check if after deadline
        $now = new DateTime();
        if ($now > $deadline) {
            Craft::$app->getQueue()->push(new ResaveElements([
                'description' => Craft::t('app', 'Resaving {section}, {type} entries', [
                    'section' => $section, 'type' => $entryType->name,
                ]),
                'elementType' => Entry::class,
                'criteria' => [
                    'siteId' => $site->id,
                    'sectionId' => $section->id,
                    'typeId' => $entryType->id,
                    'status' => null,
                    'enabledForSite' => true
                ]
            ]));
            echo "Resaving entries\n"
        } else
            echo "Not resaving entries\n";
        }
    }
}


Get all available asset transforms Is there a way to get all available image transforms in a template?
I would like to generate the srcset for responsive images programmatically.

I thought of creating a macro for that but haven't found any information about how to loop over all the registered image transforms.

Craft 3 PHP

$transforms = Craft::$app->getAssetTransforms()->getAllTransforms();
foreach($allTransforms as $transform){
    echo $asset->getUrl($transform->handle);
}

Craft 3 Twig

{% set allTransforms = craft.app.getAssetTransforms.getAllTransforms() %}
{% for transform in allTransforms %}
    {{ asset.getUrl(transform.handle) }}
{% endfor %}

Craft 2 PHP

$allTansforms = craft()->assetTransforms->getAllTransforms();

Craft 2 Twig

You'll need a plugin for this because you don't have access to that component

{% set allTransforms = craft.pluginHandle.getAllAssetTransforms %}

And in your PluginVariable

public function getAllAssetTransforms(){
    return craft()->assetTransforms->getAllTransforms();
}


Exclude a block from appearing on a specific page I'm currently trying to make my navigation be not included on my index page due to my loading a different style of page - but - include it on every other page. My current layout looks like so:

_layout.html

{% set exclusions = ['index'] %}
{% if craft.request.firstSegment not in exclusions  %}
    {% include '_navigation' %}
{% endif %}

But this seems to not work on my "index.html" page. Do I need to set it a title? or set an exclusion name here?

You can check against the Entry Type as well.
I would try to validate it with something like:

{% set exclusions = ['home'] %}
{% if entry.type not in exclusions %}
....


CRAFT_BASE_PATH problems when installing Craft 3 in subdirectory My client wants Craft 3 installed in a subdirectory of the main site. So I placed it in http://mainsite.com/subdir.

The issue now is that the webroot for the domain is at http://mainsite.com, so my Craft index.php isn't being hit when I go to http://mainsite.com/subdir since it's further down in the /web folder.

I'm trying to pull my index.php out of /web and into the /subdir directory by setting a custom CRAFT_BASE_PATH, but I've tried several different paths to no avail.

The error is simply: "This page isn’t working. mainsite.com is currently unable to handle this request. HTTP ERROR 500"

My directory structure is:

var/www/html/subdir/
├── craft/
│   └── config, vendor, templates, .env, web etc
├── index.php

But if it would be better if I stuffed index.php back into /web and went about this a different way I'm all ears. I'm not the network admin, so if there is a way to set a custom root for a subdirectory on the server or something, I'll have to ask someone else to do it for me, which is fine if that's the best way to do it.

If I understand correctly, take the content of web and place it in subdir so you have:

html/
├── subdir/
│   └── craft/ (config, vendor, templates, .env etc)
│   └── cpresources
│   └── .htaccess
│   └── index.php
└── the main site

Then in index.php do :

define('CRAFT_BASE_PATH', dirname(__DIR__) . '/subdir/craft');

And you should have your craft site accessible at mainsite.com/subdir


Can I assign an image for a product type listing page? I'm currently building a site using Craft and Craft Commerce. And when working between the two, I'm looking to make a page that shows all the products from a product-type, and have the header image change to reflect whichever product-type it is.

I know it is currently possible to make a category, assign an image to the category, and then add a category entry field to a product, allowing to organize products that way, but it seems terribly redundant, having to both put a product in a product-type, and then to also assign a category.

Is there any way to simply assign an image to the product type?

I would say it's intended that you use Craft's in-built system for product classification/hierachy/taxonomy - i.e. Categories.

Categories have support for custom fields of course, thus you can add backend manageable category images easily using an assets field, and you can also leverage all the things categories can offer without requiring anything extra from Commerce.  And any plugins etc. that work with Categories then work out of the box with your products, too.  Indeed, with Craft's neat separation of Category Groups, this still allows for good separation of your products from the rest of your data (whatever that might be, blogs etc).

I would recommend Product Types instead for managing separation of data concerns more so than product classification.  That is to say, if you have products requiring clearly different data (e.g. your sell monitors, and printers - these clearly require different lists of specifications) - that's a good use of Product Types allowing you to have the specific fields you need for these things nicely separated.

In addition to specific product types where your data determines you need them, we find it handy to have generic product and product with variant types to cover those sundry things that don't fit neatly into the various data separations we've made - with these things having just the core fields that all your products share.


GuestEntries plugin problem. So I just installed the GuestEntries Plugin.
Whenever I submit the form, I get

"POST param “sectionId” doesn’t exist"

      <form method="post" action="" accept-charset="UTF-8">
        {{ getCsrfInput() }}
        <input type="hidden" name="action" value="guestEntries/saveEntry">
        <input type="hidden" name="redirect" value="success">
        <input type="hidden" name="opiniones" value="3">
        Title
        <input id="title" type="text" name="title">
        Body
        <textarea id="body" name="fields[body]"></textarea>
        <input type="submit" value="Publish">
</form>

-opiniones is the section id.

-Have the section allowed for guest posts, with a user selected.

-Only other plugin Im using is the contact form 1.81

-running Craft CMS 2.6.2964 Personal

Any one can give me hand.?

Thanks

The plugin is expecting the POST parameter to be sectionId rather than opiniones. Changing the name attribute on that hidden input to sectionId should fix your issue.

The other requirements when creating entries from front-end template using Guest Entries are outlined below.

Make sure Allow guest submissions? is checked in the plugin’s settings (example.com/admin/settings/plugins/guestentries) and set a default author for the section entries will be saved to.

<input type="hidden" name="sectionId" value="3">

The value for sectionId can be determined by going to section settings in the control panel (example.com/admin/settings/sections) and clicking the name of the section you want to use Guest Entries with. The section’s ID is the last segment of the URL (e.g example.com/admin/settings/sections/3)

<input type="hidden" name="redirect" value="success">

The value for redirect is where a visitor will be redirected upon a successful submission and should be a valid path or URL.

A form field should be added for each field you want to save content to. Be sure to include any fields marked required on the entry type’s settings page (example.com/admin/settings/sections/3/entrytypes/3).

<input type="text" name="title">

title will always be the value for the name attribute for the entry’s title regardless of what Title Field Label is set to for the entry type in the control panel.

<textarea name="fields[body]"></textarea>

Custom fields will use fields[customFieldHandle] as the value for the name attribute.


Accessing the attributes of an Asset field Specifically looking at these attributes http://d.pr/i/1ilbr

I can access Alt text by {{ entry.assetHandle.first().altText }} and similarly can do {{ entry.assetHandle.first().sourceUrl }} but Source Name continues to be elusive.

I'm confused as to whether this is an attribute or part of the AssetSourceModel? Although would assume attribute given it's editable.

I'm assuming that Alt Text (handle altText), Source Name (handle sourceName) and Source URL (handle sourceUrl are all plain text custom fields you've created on your Assets.

If so, you'd be able to access sourceUrl the same as the others:

{{ entry.assetHandle.first().sourceUrl }}

They definitely aren't attributes on Craft's AssetSourceModel.


How to output first segment title/channel name of entry? For example, I have channel entry https://site.dev/news/2017/test and I would like to output "News" section name on entry page.

Unless I'm misunderstanding, it should be as simple as:

{{ entry.section.name }}


Save the form if not complete and come back another time to complete the form I am using the FormBuilder plugin and I want users to be able to fill in a form. If they abandon the form without completing it or submitting it, I want the form to be saved and when they login and return to the form I want the user to be able to continue where they left off.

I am fairly new to Craft CMS and Twig so I don't know where to start with this or if this is even possible in Craft.

Thanks in advance!

The FormBuilder plugin has no option to edit a submitted form. I think the best way is to use a channel in Craft CMS and write your own form. You can find the documentation on how to create/edit entries in frontend here: https://craftcms.com/docs/templating/entry-form.


Storing variables in a plugin This is a super basic question...

I've got a plugin that watches two events, in one event it creates a user. After another event I want it to activate that user.

How do I get/store/pass the id of the newly created user from the first event to the second?

public function init()
{
    craft()->on('thing.beforeEvent', function(Event $event){
        // Save the new user if they're not already a user
        if(!craft()->userSession->getUser()){
            $newUser = new UserModel;

            $newUser->firstName = craft()->request->getPost('firstName');
            $newUser->lastName  = craft()->request->getPost('lastName');
            $newUser->username  = craft()->request->getPost('username');
            $newUser->email     = craft()->request->getPost('email');
            $newUser->password  = craft()->request->getPost('password');

            $newUserSuccess = craft()->users->saveUser($newUser);
            if (!$newUserSuccess)
            {
                Craft::log('Couldn’t save the new user', LogLevel::Error);
            }
        }
    });

    craft()->on('thing.afterEvent', function(Event $event){
        // Activate the new user if they're not already a user
        //if(!craft()->userSession->getUser()){
        //  craft()->users->activateUser();
        //}
    });
}

Declare a private variable inside your class, private $userId = NULL

After you've saved the user in the first method, update the variable $this->userId = $user->id

In the second method grab the user by using the variable $user = craft()->users->getUserById($this->userId);

I haven't actually tested the code, but it might do the trick :)

EDIT: You might want to make a null-check before attempting to fetch the user, to ensure that it doesn't break if it tries to run it while the variable is still NULL


Craft 3: Can't backup database ("mysqldump: command not found") I just tried to export the DB on the Database Backup page. Unfortunately, I got an error message saying "There was a problem backing up your database. Please check the Craft logs."

So I checked the logs, and found this...

  Could not create backup: The shell command "mysqldump --defaults-extra-file=/mysite/storage/runtime/temp/my.cnf... failed with exit code 127: sh: mysqldump: command not found...

(There's more to that error message, but I'm hoping that all the relevant parts are included here.)

What am I missing? It seems like I still need to install something else, is that correct?

Craft 3 did away with the PHP-based database backup solution that Craft 2 utilized (for many reasons).

Now it requires that the mysqldump executable (if you're using MySQL) or pg_dump executable (if you're using PostgreSQL) is available to PHP in order to do backups.  This is usually just a matter of including the path to that executing in your PATH environment variable.

There is also the backupCommand config setting that you can use to override Craft's default backup implementation if you have some other backup solution you'd like to use.

Same for restoreCommand.

Related issue here: https://github.com/craftcms/cms/issues/1369


Is there a way integrate redactor with your assets fields? Does anyone know if there is a way to extend redactor to render a template, for example, when inserting an image so that it could also display custom asset fields (i.e. caption, photo credit, etc.) in a small html block? I have no idea how difficult or easy it is write redactor plugins.

A better way to tackle something like this would be to use a matrix instead of just a rich text area.

With a matrix you can have an image block and then in your template you can pull any info you want from the images custom fields.

We normally have at least three block types with a normal matrix, text, image, and gallery.

Text is just a refactor text block.  Image is an image with a "position" field to control alignment (float left/right/center) the a gallery block which lets you select a series of images which display in a slideshow


Entries search without using asset fields I have a search form on a website to search through all the entries of the website and return the entries that match the search query.

But the search query is also used on asset fields within an entry. Which for the companies channel results in many entries found when you search on the word: logo.

I like to know if there is a way to search through all the fields of an entry, but without looking through the asset field type?

So for the companies example, I only want to find entries that match the word: logo. When that word is in the content text, and not in an asset name/title.

My code now is this, but it returns the asset fieldtype result as well:

{% set entries = craft.entries({ section: 'not comments' }).search( query ).order('score') %}

As suggested in this stack post, you could specify each field individually. I haven't done this with fields, but often do so with sections and entry types in global site searches. It is kind of annoying, but I'm not sure there is a way to do this using Craft's API.


Property "Craft\WebApp.assetUpload" is not defined I came across error Property "Craft\WebApp.assetUpload" is not defined, when registering users from front end. Is this a bug or missing config param?

I have used the example on craft website:
https://craftcms.com/docs/templating/user-registration-form

The Actual template used is:

Membership Registration

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

    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="">

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

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

Username

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

    {% if account is defined %}
        {{ errorList(account.getErrors('username')) }}
    {% endif %}

Email

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

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

Password

    <input id="password" type="password" name="password">

    {% if account is defined %}
        {{ errorList(account.getErrors('password')) }}
    {% endif %}

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

Cheers,
Sil

You won't need the enctype="multipart/form-data" part of the form, since you don't appear to be uploading any files when saving the user.

Other than that, I'd guess that maybe you've got an Asset field on your User's field layout that set to required and you're not taking that into account on the front-end?j


Entry within multiple sections I'm trying to work out if the following is possible in Craft.

Assuming I have a single entry, I want to theoretically tag it as a 'blog' and 'about', both of which are sections
I want to then have that entry displayed within both the blog, and the about sections.

From what I can tell an entry is constrained to it's parent section. But is this possible using tags or something similar?

Ideally a craft2 answer, as the site is being developed in craft 2, with the plan to upgrade to craft3 in the summer.

Thanks!

Tim

UPDATE

I feel like I need to describe the problem more, with an example.

Say I have an entry called 'Meet the team', and two sections 'England' and 'U.S.A', the country sections act like normal structure sections - but the Staff Team entry is applicable to both sections.

Is it possible when displaying the England entries to display the Staff Team entry in addition to the USA entries to display the Staff Team entry?

The site in development is planning on having many of these types of pages - so a hard-coded solution to 'get' the post isn't possible.

Another way of describing it is the Wordpress way, of having 1 page in multiple categories, so each category shows that page.

When it's only for frontend: you can search for entries from different sections with

set entries = craft.entries.section(['blog', 'about', 'foo']).find()

This returns you all enabled/active entries from all the sections with the handle blog, about or foo.


Craft is unable to transfer your license to this domain at this time We have a Craft Pro (Craft CMS 2.6.3004) website that has a number of aliases on the URL. For the purpose of this the main URL is awesome.zone which has an alias of myawesomesite.com.

Recently it has started showing the "The license location at config/license.key belongs to myawesomesite.com" when logged into the admin panel of awesome.zone.

Evidently it was registered on the Alias initially, so I went to transfer the domain, but Craft won't do it.

  Craft is unable to transfer your license to this domain at this time.

What's changed recently that my license is suddenly complaining (but has been fine for 2 years) and how do I fix it?

Thanks.

With the launch of Craft ID, you can no longer transfer a license to a new domain directly from a Craft installation.  You can create a Craft ID account and from there, you can manage all of your Craft licenses, orders and download order receipts for previous orders.

This will also allow you to transfer the licenses that you own to other domains.


Combine Eager-Loading and relatedTo(category) For a website I'm building for a client I've build a navigation where on hover an image changes dynamically to the image assigned to the entry. See this page for a better understanding: http://sandmandance.com/dev/projects/performance

It all works fine but at first page load the images are only loading when hovering over the navigation which causes a small glitch. What I'd like to do (and seems like the easiest solution) is to load all the assets on page load using Eager-Loading.

Thing is.. I can't seem to combine it with relatedTo(category). So in short; how can I combine Eager-Loading and relatedTo(category) in a way it works?

I usually like to use the .find() method and then you can pass in an object in your twig with criteria for the query. This is an example of eager-loading and relatedTo.

{% set entries = craft.entries.find({
    section: 'articles',
    with: ['featuredImage'],
    limit: 4,
    relatedTo: category
}) %}

Let me know if this helps at all otherwise I'd be happy to dig into your use case more.


Craft Commerce: Creating Customer Accounts? I just want to confirm how accounts are created for customers in Craft Commerce.

Currently in the the Craft Commerce download the checkout processes provides the option to "login" or proceed with as a "guest" just providin the email. Is this the method of creating a customer account OR do we have to activate public registrations and point people to a registration page?

I'm a little unsure what needs putting into effect here. Any documentation people can point me to would be useful.

Yes, if you want users to be able to register, you would need to allow public registrations and implement your own standard registration form:

https://craftcms.com/docs/templating/user-registration-form

When they enter their email as a guest (anonymous) user a 'guest' customer record is created and related to the current cart, but it is not associated with a craft user account. This customer record is not retrievable and is only created for the purpose of having a related customer to the current order. There is no way to see this customer record in the back-end.

If the user is logged in a related customer record is created that has a 1:1 relationship with the user. The same customer record is used every time the useris logged in. This customer is the central place that addresses and orders are related to. If you want to see the previous orders for a customer, add the "Customer Info" field to your user profile custom fields.


Custom Token Authentication with Craft 3 Login Form I am building token auth system in Craft 3.
https://docs.craftcms.com/v3/dev/examples/login-form.html
I used this Login Form.

Now I am going to create my own token and save it in user profile.

First problem is to link this Form Submit Action to my custom action.
I can not find the controller linked to this action.

How can I customize my login system? Where can I find the controller for the built-in login form logic?

The submit action is the actionInput input {{ actionInput('users/login') }}.
This will call the login method of the src/controllers/UsersController and perform the action.

You may also take a look at User Element & Events where you can listen on various user events like EVENT_BEFORE_VALIDATE, EVENT_BEFORE_AUTHENTICATE etc.


Load Balancing Craft CMS - Admin gets logged out instantly We are load balancing 2 servers hosting an identical Craft environment.

When clicking around in the admin a user will get logged out after 30 seconds and sometimes even faster when browsing in the admin panel.

I am unable to set the load balancer to sticky sessions due to the load balancer sitting behind a Firewall which NAT's inbound traffic. So the load balancer see's all inbound traffic as a single IP.

Is there anything else that can be done to resolve this issue?

If you can't enforce sticky sessions, then you'll need to provide a common place for all load balanced web server to save their PHP session files.

By default PHP session files are file based and saved to whatever path the php.ini session_save_path is set to.  You could change that to an NFS share path.

If you had an in-memory key=>value store (like Redis, Memcached, etc.) you could configure PHP to save its sessions there.

If you wanted something more persistent, you could configure PHP to save sessions in a database.

On top of that, if you're not using stick sessions, you'd want to set a consistent appId and validationKey across every web server so they can decrypt Craft/PHP cookies using the same tokens.


No live preview available when entry status is set to disabled? I have a few entries which are set to disabled. It seems that the live preview is not working then. It only works when the entry status is enabled.

This seems more like a bug than a feature, right?

Update

I have checked everything again and all conditions stated by Brandon below are met, but now I see that I actually don't use the "entries own url" setting. It's enabled, so I get the live preview button, but I use dynamic routing to create my own url's (because I need to add a category as a segment in the URL).

So that's probably where it goes wrong. I check the last segment of the URI as the slug of the specific entry and set my entry manually by it.

So how do I make live preview work than?

Live Preview will be available when the following are true:

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

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


Plugin Settings Color Input Javascript Event Listeners Is it possible to attach JavaScript event listeners to the colour input field in a plugin's settings page, so that when a user selects a colour with the picker I can run an AJAX request?

If this is your plugin, you can register an AssetBundle with custom CSS and JS for your plugin. This will be loaded in your plugin settings page, and in your JS file you can then specify an event handler for your colour picker. You might need to add a specific class to the input in the settings template to ensure you can select it easily in your JS file.
If this is referring to a first/third-party plugin, you could use a plugin like CP JS to load a custom JS file into the CP and attach an event handler in that file to trigger your XHR.


Duplicating fields in Freeform Im building a form in freeform and it is going to contain many state select dropdown fields. Is there any way to duplicate this field so I do not have to populate the options/values manually every time I use that field?

Not manually but you can search for the field in your database. If the plugin uses the normal craft_fields you can copy it's settings and paste it in a new record


Can't seem to output fields related to the current category page I'm struggling to output images and other fields that are related to the current category page.

So {{ entry.title }} is outputting as expected, and displays the title of the related items to that category. But any other fields do not output.

{% set shopEntries = craft.entries.section(shop).relatedTo(category) %}
{% for entry in shopEntries.limit(16) %}

    {% set image = entry.shopImage.first() %}

    {% set shopImageTransform = craft.imager.transformImage(image,
    { width: 130, height: 170, mode: 'crop', position: 'center-center', jpegQuality: 90 }
    ) %}

{% endfor %}

This snippet is appearing on a category page, e.g domain.com/category/fashion.

Specifically for the image, if I'm correct, you're trying to use imager the wrong way.

It should be

   {% set image = entry.shopImage.first() %}
   {% set shopImageTransform = craft.imager.transformImage(image, { width: 130, height: 170, mode: 'crop', position: 'center-center', jpegQuality: 90 }) %}

Basically, 'shopImageTransform' becomes the new 'image' so you have to call .url on shopImageTransform instead of on image. You can see an example here , in the Imager readme.

As for the problem with the shopUrl, if you just dump it out, what do you receive? Is it holding any value?


Routes + Expired + Slugs I have a listing of entries at /events that loads events/index

I also have a custom route setup to be able to list 'live' entries by week

'events/(?P<year>\d{4})/(?P<week>\d{2})' => 'events/_weekindex',

I also have a page events/past that should load past entries by loading the template events/past

That all works exactly how it should. UNTIL i set a route for events/{slug} to use the template events/_entry where i have this defined at the top of the template to allow for entries expired or live to be shown without a 404.

{% set entry = craft.entries.section('events').slug(slug).status('live', 'expired') %}

Once that route is set, going to events/past no longer loads the events/past template it now attempts to load the events/_entry template. This obviously throws errors as there is no slug defined given /past is suppose to be a listing page not a single-entry page.

Also if i do load an expired entry i get an error "Variable "slug" does not exist". Do i need to specify which segment the slug is in instead of just doing (slug) have a pre set defining slug as craft.request.getSegment(2) ?

So at the end of the day i have 2 problems here. 1 the slug is not defined based on that set. And 2 the route is causing events/past to be re-directed even though it should not be.

I should note i tried also setting a route for events/past to route to events/past template but that did not do anything. I should also note the other route i set for the year/week still works after setting the other route for events/_entry, that route is not effected at all and continues to function properly.

Posted this in the slack but I think everybody is sleeping, holding my breath people are still awake on the stackexchange. :-)

UPDATE:: I set the route for events/past BEFORE the route for events/{slug} and now the events/{slug} route does not interfere with the events/past route (that i did not even think should be necessary in the first place, nor did i know that the order mattered, is this intentional or a bug?

Update 2 I've resolved the issue by wrapping everything in a for loop instead of using set like so:

{% for entry in craft.entries.section('events').slug(slug).status('live', 'expired') %}

Doing the set as listed above did not work. So my pages are now working but i'd still like some clarification on the routing, the set, and the slug issues i was having regardless. Although everything is working it almost feels like i'm doing a work-around rather than how it's SUPPOSE to be done.


Sorting entries based on an a bespoke algorithm We have been asked to scope a solution for a new site build that we'd like to use Craft for. There is one requirement I'm not sure how we'd approach though.

In Craft terms, we would have an Articles channel that has a number of fields:

Employer (relationship to a single Employer channel entry)
Sector (relationship to a single category)
Stage (select field)
Tag (tag field)

Then each logged in User would also have the same fields on their profile. I guess it would be easy enough to query the user attributes and pass those to a craft()->entries() call, but the requirements call for a very specific sorting algorithm.

That would work something like this:

Article Employer matches User Employer = score of 10
Article Sector matches User Sector = score of 3
Article Stage matches User Stage = score of 4
Article Tags intersect with User Tags = score of 1 x number of matches

The result of that score would then be added up and used as a sort dimension against a list all the latest Article entries.

Can anybody suggest a practical (processor efficient) way to achieve this?

My current thinking this:

Get all Article entries.
Loop through each Article them and add the calculated score to an array containing the entry ID and the score.
Order the array by score.
Requery all Articles with pagination enabled, passing in a the list of entry IDs in the order defined by the sorted array.

Would that work? In particular the last step - can we define entries be sorted by an array of ID numbers?

Any other suggestions would be gladly received.

Looks like a solid plan to do this. And to get the entry models it the same order as you're passing the IDs to your ElementCriteriaModel there's this property: fixedOrder(true).

Other suggestions could only be to do this with plugin code, but I don't think this would speed up thing noticeably.


Craft CMS 3 Rich Text Editor Is there a rich text editor for Craft CMS which supports both HTML source code edit as well as adding images by URL (not uploading to assets)?

You can do it with Redactor.

You can configure your toolbar to have a view HTML button.

Also, a caveat, Redactor has an html-purifier function, which will eat some bits of code in the name of making it "clean." But that's relatively easy to configure as well. Just make sure to look at the plugin documentation.


Duplicate content from www and non-www I am getting duplicate content issues because both www and non-www are being loaded.
My htaccess has the standard force https as all my other sites but it isn't working.
# START Force https
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteCond %{HTTP_HOST} ^(www\.)?geniusesforhire\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.geniusesforhire.com/$1 [R=301,L]
# END Force https

Could anything in Craft be causing this or is anything in Craft able to fix this?

2 options to avoid duplicate content:

add a canonical tag to your HTML
redirect non-www to www or vice versa


Select statement validating as true when no value selected? I have a plugin with record and model both setting required to true for a frontend form entry:

'fieldName' =>  array(AttributeType::Name, 'required' => true),

However it is still validating the select option even when there is no value so:

<select id="fieldName" name="fieldName">
    <option>--select one--</option>

or

<option value=''>--select one--</option>

Still validates as true.

How can I get around this?

You could try setting a minimum length:

'fieldName' =>  array(AttributeType::Name, 'minLength' => 1, 'required' => true),


Any way to create new entry using certain entry type? I'm thinking this isn't possible but would be nice if it were?

Just wondering if you have loads of different entry types for a section then it would be nice if there was a way of creating a new entry with a certain entry type instead of having to go to create a new entry and then select the entry type.

Would be slightly less confusing for clients and would stop some errors in that they would hopefully always get the right entry type instead of typing into the first entry type that shows up.

I assume you're talking about from the control panel?

If that's the case, then the answer is no.

But it sounds like you're asking for a way to maybe set a default entry type?

Regardless, this sounds more like a feature request.


How do I check if a product has stock in any of it's variants? Basically, I'm trying to show "Out of stock" and disable a button for when none of the variants have stock, and unlimited stock is unchecked.

I've tried this, which isn't working:

{% if product.variants.stock <= 0 and product.variants.unlimitedStock == false %}
    {{ "Out of stock"|t }}
{% else %}
    {{ "Add to cart"|t }}
{% endif %}

I managed do this with the following:

{% set variants = craft.commerce.variants({
    product: product,
    hasStock: true
}) %}

{% if variants|length <= 0 %}
  Sold out
{% else %}
  Add to basket
{% endif %}

The hasStock criteria takes unlimitedStock into consideration.

if (isset($criteria->hasStock) && $criteria->hasStock === true)
{
  $hasStockCondition = ['or', '(variants.stock > 0 AND variants.unlimitedStock != 1)', 'variants.unlimitedStock = 1'];
  $query->andWhere($hasStockCondition);
}


Only see 3 textarea field on Plugin Setting Page I am developing the plugin to send user difference confirmation email which more than 20. I put those fields in templates/settings.html so that the admin could change and update the message content. However, after I put more 3 textareaFields, I only able to see 3 Textarea display on the setting page. The 4th one does not show up. Does anyone know how to solve that issue? Thanks

{{ forms.textareaField({
    label: "Customer Account Creation Confirmation Message"|t,
    instructions: "Customer email message when customer register" |t,
    name: 'custAccountCreation',
    value: settings.custAccountCreation,
    rows:5,
})}}

{{ forms.textareaField({
label: "Customer Account Appointment Confirmation Message"|t,
instructions: "Customer email message when customer appointment confirmed" |t,
name: 'custApptConfirmed',
value: settings.custApptConfirmed,
rows:5,
})}}

{{ forms.textareaField({
label: "Customer Appointment Reminder with Vet Identification"|t,
instructions: "Customer Appointment Reminder with Vet Identification" |t,
name: 'custApptReminder',
value: settings.custApptReminder,
rows:5,
})}}

{{ forms.textareaField({
label: "Customer Appointment Reminder with Vet Identification1"|t,
instructions: "Customer Appointment Reminder with Vet Identification1" |t,
name: 'custApptReminder1',
value: settings.custApptReminder1,
rows:5,
})}}

After shuffle all textareaField, I found the 4th one custApptReminder1 misspell in function defineSettings() at my plugin.php. After corrected it, the field is show up.

protected function defineSettings()
    {
        return array(
            'custAccountCreation' => array(AttributeType::String),
            'custAccountCreationSubject' => array(AttributeType::String),
            'custApptReminder'=> array(AttributeType::String),
            'custApptReminder1'=> array(AttributeType::String),
        );
    }


Is it possible to convert a plain text field to a rich text field, without losing content? I originally had some content stored in a plain text field but I want to give my co-workers the ability to add anchor links, lists etc..

If I were to change the field type form Plaintext to Rich Text would I lose that content?

Also right now to output it, I am using the following :

<p>{{ entry.field }}</p>

so I would have to change that to just using

{{ entry.field }}

Will converting it to rich text, automatically add paragraph tags for me or would I have to go into each one and resave?

You should be OK converting your Plain Text to Rich Text. I've just tried it in my dev environment and everything was preserved.

Rich Text will add the paragraph tags as you suggest, so you'll want to remove them from your templates files as you mentioned.

If you're being cautious, you can take a backup of your database in the Settings section of your control panel before changing the field type. It only takes a few seconds, and that way, if anything goes wrong, you can restore.


Craft Panel Structure Duplication Issue Having a weird issue here.

I have a structure field inside my section on my panel which is divided up by headings.

The issue I'm having is that when I try to collapse a heading via the panel, it doesn't have any effect. It doesn't collapse and sometimes it makes a duplicate of itself.

Its a hard issue to explain over text so I've created a small video to show the issue in action.

https://www.youtube.com/watch?v=vv8vToRCUUw&feature=youtu.be

Any help would be appreciated.

Thank you

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

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

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

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


How do I add custom styles/plugins to the rich text editor in Craft? I'm aware that I can customise which buttons is available in the rich text editor. But how can I add custom css styles, either as classes or as inline styles? Do I need to create a plugin for this? If so, how do I add plugins? And, can I change which options are available in the formatting drop down?

If by styles you mean the formatting drop-down, just add them in an array:

{
    buttons: ['bold', 'italic'],
    formatting: ['p', 'blockquote', 'h2', 'h3', 'h4', 'SomeHtmlTag']
}

.

If you want to have a button which adds custom CSS-classes, take a look at: Redactor CSS by Nathan Doyle

Update (July 2015)

Craft 2.3.2615 (Dec 2, 2014) and above use Redactor 10, which includes the formattingAdd setting for adding custom styles and classes.

formattingAdd: [
{
    tag: 'p',
    title: 'Red Block',
    class: 'red'
}


How can I add Google MarkerClusterer library to Smart Map? I started to work with Craft CMS a couple month ago, I have a client that wants to have a clustered map, I went over Smart Map documentation but I couldn't find anything about on how to add Google MarkerClusterer library.

UPDATE
It looks like the underlying MarkerClusterer library has been moved (and theoretically improved).
The new library can be found here...

https://github.com/googlemaps/js-markerclustererplus

Not sure how much that affects the original JavaScript example below, but it's probably still a reasonable starting point.

ORIGINAL
As Jalen mentioned in his answer, this functionality isn't (currently) built into Smart Map. However, it's very easy to add yourself...
First, you'll need to add the MarkerClusterer library to your map page. You can link to it normally, just as you would with any other JS library.
Once you've got the library installed, you'll be able to cluster your markers with code as simple as this:
var map = smartMap.map['smartmap-mapcanvas-1'];
var markers = smartMap.marker;

var markerCluster = new MarkerClusterer(map, markers);

Pretty much everything else happens automagically!


Home page won't load without 'index.php' On a fresh install of Craft 2.3.2644, using the hostname alone, example.com returns an error, "The page cannot be displayed because an internal server error has occurred".

If I include /index.php (example.com/index.php), then the expected index template is returned, displaying the "Welcome to..." entry.

However, example.com/news returns the news template correctly, even without index.php in the URI.

Craft 2.3.2644
Windows Server 2008 R2
IIS 7.5

The web.config file included with the Craft install is present at web root.

What am I missing?

If I recall, IIS doesn't include index.php as a default document when looking for a page to load in a directory, but only things like index.html, index.htm, deafult.html, etc.

Here's how to change it.


Get CP's current selected locale Is there an easier way to get the CP's currently selected locale? In my plugin I am currently using this method.

public function getCurrentLocale() {
    $id = is_array($this->value) ? $this->value[0] : false;
    $segments = craft()->request->segments;
    $lastSegment = end($segments);
    $locales = craft()->elements->getEnabledLocalesForElement($id);

    if (in_array($lastSegment, $locales)) {
        return $lastSegment;
    }

    return null;
}

I assume this is in the context of an event, in which case you've got access to the EntryModel.

If so, $entryModel->locale should be what you're looking for.


Get model changes on save event If an model/element gets changed then I can know about it by listening to an event like onBeforeSaveEntry. This will provide me with the latest version of the model/event, but doesn't give me the changes. Something like this would be great.

craft()->on('elements.onSaveElement', function (Event $event) {
    $element = $event->params['element'];

    // $changes = ['uri' => ['old' => 'index', 'new' => 'index2']]
    $changes = $element->getUnsavedChanges();
}

I generate a routes.js that the client uses to generate menu and other stuff. I would like to listen to uri/slug changes so I can clear my (varnish) cache to update internal links. I'd like to prevent clearing my whole site if just one tiny thing gets changed. Any idea's how I can get the model changes or work around this issue?

You have to listen to the onBeforeSaveEntry event, then query the database for the existing entry (if one exists).

craft()->on('entries.onBeforeSaveEntry', function(Event $e)
{
    if(!$e->params['isNewEntry'])
    {
        $updatedEntry = $e->params['entry'];
        $currentEntry = craft()->entries->getEntryById($updatedEntry->id);

        if($updatedEntry->getUrl() != $currentEntry->getUrl())
        {
            // Do your thing
        }
    }
});

It might also be worth checking if the updated entry even has a URL, so you could skip that DB query if you don't need it.

You have to be careful with this event though - there's always the possibility the transaction could fail and the updated entry won't get saved to the DB. In that case, you might want to also listen to the onSaveEntry event (if you're doing anything other than writing to the DB - this would get rolled back automatically if something fails) as a way of checking if everything went okay.


Getting PHP Error on upgrade from 3.0.36 to 3.1 I just updated to 3.1 and I'm getting the php error:

PHP Notice – yii\base\ErrorException

Undefined index: settings

It probably has to do with the Cheat Sheet plugin.  I deleted that folder in the vendor directly but no luck.

I can send along the link showing the errors.

Thank you!

If you restore from a 3.0.36 database backup, then update to the latest Craft 3.1 release (currently 3.1.2.2, this shouldn't be an issue anymore.


Filter users: in group AND not in other group Please could you advise on how to filter a user query, so that users from Group A are included, but not if they are also in Group B?
{% set vnp_users = craft.users
    .group(['groupA', 'not groupB'])
    .orderBy('field desc')
    .all() %}

I'm not sure you can do that in one query only but I might be wrong.
Using two queries, you could do the following:
{# Fetch users from the group you don't want to display #}
{% set usersToExclude = craft
    .users()
    .group('groupToExclude')
    .ids() %}

{# Built an array of ids to exclude adding 'not' to it #}
{% set exclusionList = ['not'] | merge(usersToExclude) %}

{# Fetch your users excluding the one found above #}
{% set vnp_users = craft
    .users()
    .group('groupYouWant')
    .id(exclusionList).all() %}


File upload error in MS Azure after custom domain was pointed to Azure server I am facing an issue with file uploads. I installed a new installation of Craft CMS on Microsoft Azure server. MS Azure assigns a default domain to your webapp like example.azurewebsites.net.
So while the default domain was assigned, I uploaded few asset files (images) successfully.

Later we had a custom domain added to Azure like mydomain.org
Once the custom domain was mapped, I edited the SiteURL (in Settings -> General -> mydomain.org) to the custom domain.
Now I am unable to upload asset files.

The error log shown in the Craft CMS craft.log (from Server Info) is move_uploaded_file(): Filename cannot be empty (D:\serverpath\craft\app\assetsourcetypes\BaseAssetSourceType.php:170)

Can someone please help.

MS support team helped to resolve the issue. I will post the steps to be followed.

In your CMS Admin, Under Assets source ->
File system path: images/
URL: http://example.azurewebsites.net/images
(Here the images directory is under public directory)
In Azure portal, Add the following App settings in Application setting of your App service:
key: WEBSITE_DYNAMIC_CACHE
value: 0
Restart the Azure App service.


Feed Me finds no elements to process Feed Me gives me, out of the blue, the error message below. I realized it only because i had "disable missing elements" active and all my entries where disabled. Feed Me was running over months without errors. I also made no changes to the Feed Settings at all.

Can anyone explain that to me? Thank you!

There is a pull request on github for this. You can see what to do here if you want to fix locally until an update is released.


Limit ElementAPI results with custom date/time field What is the proper syntax in the ElementAPI 'criteria' configuration settings for limiting entries based on custom start and end date/time fields. I can't use the default postDate and expiryDate due to localization requirements.

I have the proper syntax working in my twig template:

.startDateTime('<=' ~ now.date,':empty:').endDateTime('>=' ~ now.date,':empty:')

How can I mimic this same logic in the ElementAPI config settings? This is what I have so far. It doesn't throw any php errors but doesn't return the results I am expecting:

'criteria' => [
    'section' => 'mySection',
    'type' => 'mySectionType',
    'startDateTime' => '<=' . date("Y-m-d H:i:s") . ', :empty:',
    'endDateTime' => '>=' . date("Y-m-d H:i:s") . ', :empty: '
],

After some exploration and trial and error, I was able to find a solution. Ultimately there are two problems:

startDateTime, endDateTime and php’s date() function were not returning the same timezone date & time.
The correct formatting for matching multiple values needs to be in an array.

The fix:

At the top of my elementapi.php file I added this line to make sure php’s date() function returns the same timezone craft has been set to in the admin config.

date_default_timezone_set(craft()->timezone);

Then I reformatted my criteria settings as such:

'criteria' => [
    'section' => 'mySection',
    'type' => 'mySectionType',
    'startDateTime' => ['<=' . date("Y-m-d H:i:s.u"), ':empty:'],
    'endDateTime' => ['>=' . date("Y-m-d H:i:s.u"), ':empty:']
],


{% cache %} always creates new cache data, never uses existing cached data Why would the {% cache %} tag be storing a new cache every time the page loads (instead of just loading the existing cache)?

Unless I'm misunderstanding how caching works, the system should never record duplicate cache keys, correct?

Despite the data apparently getting cached, the page never feels like it's pulling from cache. Every page load feels long and sluggish.

UPDATE:

I've done some additional testing, and was able to get the caching to perform as expected. Here's what changed...

In my original version, I was caching a giant chunk of the template. This included the large database query (100+ records with 100+ fields), some Twig-side data manipulation, and the entire HTML portion of the template. Within the HTML, I am looping through those records and rendering a chunk of HTML for each.

In the new version, I am only caching the HTML loop. This is making a huge difference, bringing the page load time from ~15 seconds to ~1 second.

What I've found...

It appears that the offending line which was causing multiple cache keys to be generated is this one:

{% set entries = craft.entries.section('mySection').type('myType').limit(null).find %}

I still don't know why, and would appreciate an explanation if anyone knows!

Update:

This has been fixed for the next (post 2.4.2725) release.

Turns out there is a bug in Craft where if you put cache tags around code that doesn't actually output anything, then duplicate keys get created in the craft_templatecaches table.

No workaround for it yet (other than to make sure you don't cache an empty string), but it's been logged as a bug.


Detecting if page is a 'category' or 'entry' Is there another way of detecting if a page is an 'entry' or a 'category' than the following? Maybe some global variable that I do not know of?

{% if entry is defined %}
  <!-- Code here -->
{% endif %}
{% if category is defined %}
  <!-- Code here -->
{% endif %}

I have a html code block that is included in both entry pages and category pages hence the need for this.

Thanks in advance!

It'd be nice to see an example of your HTML block. From your comments it sounds like you may be using the same HTML block for Entry and Category pages but need to know which variable to use in the code.

Assuming you know that your code is running on the Entry or Category pages, and that the fields across both your Entries and Categories for this part of the page are the same, you can place your common HTML in an include and pass both the entry and category variable to that include with the same variable name.  In the example below, we're handing off the entry and category variables and using the variable name object in the include template:

_entry.html

{% include '_partials/shared-template' with { object : entry } %}

_category.html

{% include '_partials/shared-template' with { object : category } %}

_partials/shared-template

    {{ object.fieldName }}

    {% for item in object.someOtherFieldName %}
      {{ item }}
    {% endfor %}

If some of the field names are different, you may need to use some conditional logic or reconsider what variables are being passed to the included template.  You could pass dissimilar variables under the same variable names to a common template in the following way:

index.html

{% if entry is defined %}
    {% include '_partials/shared-template' with {
        title : entry.title,
        someOtherVariable: entry.fancyFieldOne
    } %}
{% endif %}

{% if category is defined %}
    {% include '_partials/shared-template' with {
        title : category.title,
        someOtherVariable: category.fancyFieldTwo
    } %}
{% endif %}

_partials/shared-template

    {{ title }}

    {% for item in someOtherVariable %}
      {{ item }}
    {% endfor %}


Have I accidentally relicensed my key? I've just realised that when I duplicate my boilerplate Craft site to start a new client project, I haven't been deleting the license.key file as per the docs here. What are the potential problems here? Does Craft regenerate a key file if it's already used, or have I somehow licensed a single key multiple times?

You should have seen a warning that the license belongs to another domain (https://craftcms.com/support/license-transferring).

If not; are these duplicate sites still on a non-public (development) domain? That might explain why you did not see the warning. In either case: simply delete the license file for the duplicate sites and Craft will create a new one. You might need to clear the caches as well.


How can I make Craft's caching aware of fields used inside a plugin? I have a complex template which uses various modules and sub-components for which I opted for handling all the logic and rendering directly in PHP, as it felt like it was too complex a job for twig.

Currently, when I change a field (e.g. swap out an image) inside one of the modules, the surrounding cache isn't busted, so the site doesn't update.

My question is: How can I make Craft aware of fields used inside a plugin within a {% cache %} tag, so that when a field is changed, the surrounding cache is busted?

I am aware of the TemplateCacheService, but unsure if / how I can use that in this case (I had a bit of an experiment with no success).

The modules represent a Neo field, but my assumption is that this would work very similarly if not identically to if this was a matrix field.

A super-reduced test case looks something like the following:

{% for module in modules %}
    {% cache using key module.id %}
        {{ craft.control.renderModule(module) }}
    {% endcache %}
{% endfor %}

_modules.twig

<?php

namespace Craft;

class ControlVariable
{

    public function renderModule($module)
    {
        return craft()->control_modules->renderModule($module);
    }
}

ControlVariable.php

<?php

namespace Craft;

class Control_ModulesService extends BaseApplicationComponent
{

public function __construct()
{}

public function renderModule($module)
{
    ?>

    <img src="<?= $module->myImageField->first()->getUrl(); ?>">

    <?php
}

Control_ModulesService.php

FWIW, in the following setup, the cache is successfully busted when changing the image field in the CMS:

{% for module in modules %}
    {% cache using key module.id %}

    {% endcache %}
{% endfor %}

_modules.twig

The {% cache %} tag tracks Elements (Users, Entries, Categories, Tags, etc.), so if you're want to do this using a plugin, then the plugin's field type needs to inherit from BaseElementFieldType and needs to implement its own element type.

From there, it's just a matter of calling craft()->templateCache->includeElementInTemplateCaches().


SQL Error - cannot add foreign key constraints I'm uploading a site to a new environment and getting the following error:

The assetfiles table structure:

Based on that description, my guess is you're running into #2 here (https://stackoverflow.com/a/16969176/684) and you've got some inconsistent data in one of the three foreign key constraints that the SQL is trying to add.


Performance issues in CP with +60k articles database We are are working with a large dataset of over 60k articles. The craft control panel has a very hard time loading the entries list tables. Using debug I see that the queries that takes up the longest (+10s) is the one that starts likes this "SELECT sourceId AS source, targetId AS target" . Does anyone has any ideas or tips on how we can get around/fix this issue?
This is an image form the debugger on the ajax call loading a list of entries in the contents tab.

Doing further research i noticed the performance impact is mainly due to sorting on the default publication date. When sorting on the title field all the performance issues are gone.


Rollback Plugin Version I'm looking to rollback Feedme to a previous version. I can't find any docs or information on Stack Overflow on the best way to go about doing this?

You will need to change the version in your composer.json file to the version you want (guessing 4.3.2 if you want the last version) then run composer update on the command line.


Show a partial list of sections I would like to selectively show a subset of my sections in the main navigation. Is it possible to do something like this?

{% set sections = craft.sections.getSectionById(1,2,3) %}

{% for section in sections}
...

Something like this should work:

{% set sections = [] %}

{% set sections = sections|merge([craft.sections.getSectionById(1)])
{% set sections = sections|merge([craft.sections.getSectionById(2)])
{% set sections = sections|merge([craft.sections.getSectionById(3)])

{% for section in sections %}
    ...
{% endfor %}


Task Validation Debugging I am having issues debugging craft tasks where the issue is caused by validation errors rather than php syntax / environment issues.

How do you debug validation errors in craft tasks?

Validation errors will still get logged to craft/storage/runtime/logs with a [warning] label.

Other than that, you options are just like you'd debug anything else in PHP.  Preferably with xDebug, but you can always manually Craft::log() and read the log files, too.


Error on import to Craft production db I just copied my database across from local server to production server. I used Craft's control panel to create a backup. Then I used Sequel Pro to import this into the live server.
I got this error:

  [ERROR in query 121] The query length of 4327045 bytes is larger than max_allowed_packet size (4194304).

I clicked on 'Continue' and all looks OK on my live site.
Can someone suggest what this might mean? Should I worry? What should I do?

Your MySQL configuration has its max_allowed_packet config setting set to the default 42M (4194304).

There's a query that executed for database backup that is slightly larger than that (about 44M).

You'll need to increase that value in your MySQL config or ask your host if they can do it for you if you want to import the backup without any errors.


Is it possible to use useEmailAsUsername and see User Relations Fields display as First Name + Last Name? We have a site where we want to use email addresses as the username.

The site also has a lot of related user content and the administrators on the site know many of the site members by name.

Currently, Craft User Relations Fields display the email address of each user.  This gets pretty confusing quick as recognizable names become long strings of letters and numbers after you relate them.  In some cases, we find ourselves triggering the User Relations modal just to figure out who is related to the Entry we are looking at.

We require Users to submit First Name and Last Name values so we can ensure that each user has that value. Is there any way to define what values we see for the User Relations Fields?

Currently, there isn't a native way to do that, but I can see where it'd get confusing.  I'll add it to our list to look into.


Submitting checkbox data from a front-end form for a 'Categories' Field Type I have read a few docs about front-end forms such as the Checkbox field docs.

Although that doc doesn't seem to give an example of what I need.

I have a 'categories' field type. I am creating a front-end form that will need to submit what is checked to the entry. I have tried a few different ways and can't get it to work. This is the last code I tried:

Design Tags

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

{% for category in categories %}
    <input type="checkbox" id="designTags" name="fields[designsTags][]" value=" {{ category.id }}"> {{ category.title }} </input>

{% endfor %}

I also tried changing category.title to category.id, but no luck with that either.

And before that, I tried something similar to the code at the bottom of this page (using the option.value) and it still wouldn't work.

Any help you can give is greatly appreciated! :)

I just tried your code and it worked.

Is your entry getting saved at all? If not I assume there might be another error. Add this to your code to output all form errors:

{% if entry is defined %}
    {{ dump(entry.getErrors()) }}
{% endif %}

Although it didn't made a difference in my test, you should remove the space to be sure:

value="{{ category.id }}"


Wrap embeds with HTML in rich text field When using rich text fields, is there a way to automatically wrap embedded content (specifically, videos) in some kind of custom HTML?

I'd like to, at the very least, wrap the embed in some element (a
, for instance) with some kind of class or ID, so that it'd be something like
EMBED HERE
.

I've found my way to the Craft docs for rich text fields, and see that I may be able to add this functionality via Redactor, but I'm not sure how to go about doing so.

Any suggestions are appreciated.

I suggest a Twig filter so you can do something like this in the template:

{{ entry.body | wrapembeds }}

This is something to love about Craft - the ease of building Twig filters.

In the plugins directory create a folder videoembeds.

Create the main plugin file WrapEmbedsPlugin.php:

<?php
namespace Craft;

class WrapEmbedsPlugin extends BasePlugin
{
    public function getName()
    {
        return Craft::t('Embed Wrapper Twig Filter');
    }

    public function getVersion()
    {
        return '0.0';
    }

    public function getDeveloper()
    {
        return 'Your Name';
    }

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

    public function hookAddTwigExtension()
    {
        Craft::import('plugins.wrapembeds.WrapEmbedsTwigExtension');
        return new WrapEmbedsTwigExtension();
    }
}

Create another file WrapEmbedsTwigExtension.php:

<?php
namespace Craft;

class WrapEmbedsTwigExtension extends \Twig_Extension
{
  protected $env;

  public function getName()
  {
    return 'WrapEmbeds Twig Extension';
  }

  public function getFilters()
  {
    return array('wrapembeds' => new \Twig_Filter_Method($this, 'wrapembeds'));
  }

  public function initRuntime(\Twig_Environment $env)
  {
    $this->env = $env;
  }

  public function wrapembeds($content)
  {
    $filtered = preg_replace_callback('//', function($matches) {
      return '
'. $matches[0] . '
';
    }, $content);

    $charset = craft()->templates->getTwig()->getCharset();
    $filtered = new RichTextData($filtered, $charset);

    return $filtered;
  }

}

Enable the plugin in the admin then add the filter to the template tag. Hopefully this is enough to get you started adding custom Twig filters. Simple once you know how and very handy!


Multilingual slug setup I'm setting up my first multilingual website with Craft. I'm struggling with multilingual slugs.

This is how I'd like the slugs to look like.

If I do this tough, I need to adapt my folder structure. To get it working I needed to create folder structure like this

/fr/nouvelles/
/en/news/

both containing the same templates.

Is it possible to get this working without needing to copy the templates? I'd like to always load the same template(/news/), without the language specific folder structure.

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

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

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

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

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


SearchPlus Plugin Not Syncing Indexes For the past couple of months now, I've noticed on my websites using the SearchPlus plugin that indexes are no longer syncing with Algolia. This also means that creating new search indexes is not possible.

I've been updating indexes manually via the Algolia dashboard, but this means that I can't create new indexes at all.

My best guess is that the plugin is no longer compatible with Algolia's API. Has anyone encountered this, or come up with a fix for this issue?

Algolia changed their index quotas, requiring records to be no larger than 10kb for the Community Edition plan.

My issue was solved by upgrading my to the Essential plan, and creating a custom mapping with the Search Plus plugin, to make sure I kept the record size only as large as it needed to be.

I was experiencing issues particularly with Commerce products that had variants and other custom fields.


Group by Field in Matrix Field Is it possible to group by a field within a matrix field.
I have a channel of players which holds their details.
I have a structure for teams which includes a matrix field for a Player.

The Player matrix has 2 fields:

1 - Position (Drop down with: Goalkeeper, Defender, Midfielder)

2 - Entries field linked to Players Channel.

When accessing the matrix is it possible to Group the blocks by the Position field?

You should be able to do this with Craft's handy group filter.

{% set players = entry.myPlayersMatrix %}
{% set playersGrouped = players|group('myPositionDropdown.label') %}

{% for position, playersInPosition in playersGrouped %}

{{ position }}

    {% for player in playersInPosition %}
        {% set playerData = craft.entries.section('myPlayersChannel').relatedTo(player).first() %}

            {{ playerData.fullName }}
            {{ playerData.age }}
            ...

    {% endfor %}

{% endfor %}


Craft CMS plugin route redirects to login when not logged into Craft I created a simple Craft plugin to allow for custom action URLs. Specifically, I have a path "actions/api/sendEmail" that hits a method in my plugin's controller. It sends an email from a contact form via Ajax.

This works perfectly when I'm logged into Craft in the browser. But if I am not logged in, Ajax hits the "actions/api/sendEmail" URL and then gets redirected to "/login". Is my plugin not set to be a public-facing, front-end plugin? I'm pretty new to Craft. I've read through a lot of the docs about plugins and routes but can't seem to find the answer.

Thanks in advance for any help!

Here's my plugin controller class file:

<?php
namespace Craft;

class apiController extends BaseController {

  function actionSendEmail() {

    $name = $_POST['first_name'] . ' ' . $_POST['last_name'];
    $email_address = $_POST['email'];
    $phone = $_POST['phone'];
    $company = $_POST['company'];
    $title = $_POST['title'];

    $email = new EmailModel();

    $email->toEmail = 'luke@graftonstudio.com';
    $email->subject = 'Contact Form Submission';
    $email->htmlBody = '

Contact Form Submission

                                                Name:
' . $name . '

                                                Email:
' . $email_address . '

                                                Phone Number:
' . $phone . '

                                                Company:
' . $company . '

                                                Job Title:
' . $title . '

';

    craft()->email->sendEmail($email);

    // not returning anything at the moment
    echo json_encode(array());
  }

}

You need to explicitly allow allow anonymous access to your controller's action.

More info on how to do that here: http://buildwithcraft.com/docs/plugins/controllers#allowing-anonymous-access-to-actions


Templating SuperTable I'm using the SuperTable plugin to create Matrix fields inside a super Table. It's looking great in the front-end but I can't find any documentation on how to template the fields. This is my code so far:

            {% for block in entry.informasjon %}

                {% if block.type == "innhold" %}

                    {% for row in entry.velg1Av3BildeVideo %}

                            {% for image in entry.bilde1 %}

                            {% endfor %}
                            {% for image in entry.bilde2 %}

                            {% endfor %}

                    {% endfor %}

                {% endif %}

            {% endfor %}

There's no block types with SuperTable, so no need to check that. Other that that it works just the same as Matrix fields.

{% for row in superTableField %}
    {{ row.textFieldInSuperTableField }}
{% endfor %}


entry-overview superslow after update? we have a little problem with craft after updating to the new version.
the entry-overview (foo.com/craft-admin/entries/) seems to load much slower than before when I click an entry (up to 10 seconds)
problem part 2: we just created about 100 sections, which makes the system complete unusable, as we run into timeouts by clicking certain entries.
any idea how to deal with this?

okay, guess I got it.
as soon as I kick the Preparse Field-plugin, everything works smooth. but i guess it's not the plugin that causes the trouble, it's the way craft is writing its logs for deprecated code?

another solution: RTFM..
in Preparse Field-plugin: activate "Disable all Preparse field columns on all element indices".


How to load entry-objects with Ajax I should begin to say that I have no idea really how exactly ajax works. Although I've used it a couple of times with pre-made WordPress plugins. I saw some examples of ajax entry-loading here on Stack Exchange, I tried to make ajax requests in Craft but just ended up with server errors.

My main goal that I want to accomplish is just to have a news-feed that begin to show 5 entries, a button on the bottom that appends five more.

Is it best to use jQuery for the Ajax-request?
How can I load the "next" five entries in a news-feed, so the call doesn't load the latest five entries over and over?
I've seen that you need to build a specific template for ajax-calls. Is there any good examples of those?

If someone got some advice for me how to accomplish this it would make me so happy!
It'd be really nice to learn how it works, so if you got tips of tutorials, working examples, good reads — please share :)

Is it best to use jQuery for the Ajax-request?`

Not necessarily. jQuery provides an easy-to-use ajax function, but nowadays it's perfectly simple to make an AJAX call with vanilla JS.

  How can I load the "next" five entries in a news-feed, so the call doesn't load the latest five entries over and over?

You will need to pass an offset and limit to your element query, or use Craft's paginate tag, in order to only receive data for one 'page' of elements at a time.

  I've seen that you need to build a specific template for ajax-calls. Is there any good examples of those?

I prefer to use the Element API plugin to serve up my JSON for front-end consumption... but you can also build a JSON feed using a Twig template.

Here are some links that might be helpful:

Basic intro info about AJAX
Tutorial on front-end lazy-loading with Craft ... (site appears offline at the moment, so you can also use a Wayback copy)
Element API plugin, which allows you to easily create a JSON feed of queried elements:
Other answers from SE questions about AJAX pagination/loading


Migrating a Yii site to Craft I have a large site running Yii (1.1.x), complete with many controllers for specific applications.

A big section of the site is "static" pages, which use Yii to render out using a site layout.

I'm interested in migrating the "static" portions of the site into content management, but I need to keep my applications. Is there an easy way to create Craft plugins that will call my existing Yii controllers? Or is there some other way to port the functionality without rewriting everything?

Is there an easy way to create Craft plugins that will call my existing Yii controllers?

There might be a way, but I'm not sure how easy it'd be.

I think it'd be a more guaranteed easy path if you were to take your existing Yii controllers and turn them into Craft plugin controllers, but I'm not sure of the extent and complexity of your existing application.


How to wrap a matrix blocktype occurrence loop inside a ul? I made a template including a matrix field. I want to wrap all occurrences of a certain block type into a
 element. How can I do this?

My current code:

 {% for block in entry.matrixField.all() %}
        {% switch block.type %}
            {% case 'blockType1' %}

                {{ block.field }}

            {% case 'blockType2' %}

                {{ block.field }}

            {% case 'blockType3' %}

                    {{ block.field }}

        {% endswitch %}
    {% endfor %}

Current output:

blockfield

blockfield

blockfield

But I want my output like this:

blockfield

blockfield

blockfield

That is, I want the ul tag to follow the loop of blockType3.

A possible solution could be this:
Instead of outputting your blockType3 immediately, save all blockType3 ID's in an array. When your loop has finished (check for loop.last) output all the blocktypes from the array at once.

This code is just as an example (untested):

{% set arrBlockType3 = [] %}
{% for block in entry.matrixField.all() %}
    {% switch block.type %}
        {% case 'blockType1' %}

                {{ block.field }}

            {% case 'blockType2' %}

                {{ block.field }}

            {% case 'blockType3' %}
                {% set arrBlockType3 = arrBlockType3 | merge([block.id]) %}
    {% endswitch %}
    {% if loop.last %}

        {% for id in arrBlockType3 %}
            {% set block = entry.matrixField.id(id).first() %}

{{ block.field }}

        {% endfor %}

    {% endif %}
{% endfor %}


How do I programmatically add assets to an assets fieldtype on a Matrix I have a json file with a bunch of id's & associated images.

The id's relate to existing entries in my Craft installation.

I have a Matrix field called Content with a block type called allImages - the allImages block type has a single field called images defined as an Asset field type.

What I would like to do is import the json file & update the existing entries with the images as defined in the json.

I cannot for the life of me figure out how to add images to the Matrix field in code. There are plenty of samples around submitting post variables from a custom form to the saveEntry action.

Any tips would be greatly appreciated

This is totally untested but something like this could work (or at least give you some hints)

edit: since I was bored I tested the code.. it works

public function actionImport(){
    $jsonData = // getYouJsonDatasomehow here
    foreach($jsonData as $json){
        $entry = craft()->elements->getElementById($json['id']);
        /** @var \Craft\MatrixBlockModel[] $matrix */
        $matrix = $entry->Content->find();
        /** @var \Craft\MatrixBlockModel $block */
        foreach ($matrix as $block){
            // I pretend there is already the required block for the entry otherwise you have to create it

            if($block->getType()->handle === 'allImages'){
                // long version...
                $attributes = $block->getContent()->getAttributes();
                $attributes['images'] = $json['imageIds'];
                // some other changes if you want... title or whatever
                $block->getContent()->setAttributes($attributes);

                // short version would be
                $block->getContent()->setAttribute('images', $json['imageIds']);
                craft()->matrix->saveBlock($block);
            }
        }

    }
}

Since you did not say if the blocks/entries already exist or if the images even exist or if they have to be imported as well I decided to pretend everything is ready to use and your json images contain just an array of ids. If your images contains only local paths you would have to import them first with something like

$arrImages = [];
foreach($json['images'] as $image){
    $path = $image['path'];
    $name = $image['name'];

    $response = craft()->assets->insertFileByLocalPath(
        $yourFilePath,
        $nameOfImage,
        $folderId,
        AssetConflictResolution::Replace
    );

    if($newFildeId = $response->getResponseData()['fileId']){
        $arrImages[] = $newFildeId;
    }
}

$block->getContent()->setAttribute('images', $arrImages);


Is Craft suitable for these specific document management goals? I'm trying to get a good appreciation for Craft's current capabilities and maturity. I've seen the demo and the docs but there is definitely a learning curve and what appears to be a need for much more coding - some of which I'll certainly need to hire a developer to assist regardless of platform. I see sparse videos, don't see many third party addons either, and docs suggest creating object oriented code just to set up field attributes. Thank you for any guidance in advance.  I'll share a little about my goals.

Project: I'm creating a document management system that is the same as you've probably seen in many school libraries (doc title, a long abstract that summarizes the full doc, excerpt and several taxonomies that classify docs into doc type (research paper, proposed law, etc.), country of origin, organization creating the doc, etc. It also has some doc fields, e.g. document language, date published, etc. Some primary objectives:

(1) Create relationships between docs. For example, if a document has been translated into 3 other languages I'd like to be able to recognize all those related documents in the doc and display the translated documents in a list on the front end for easy access so a user can view the doc in their preferred language.

(2) Ajax based filtering system. This has me leaning toward ExpressionEngine / Wordpress because of the availability of a very well thought out ajax-based filtering system, e.g. Low Search. Wordpress has numerous plugins, including WP-Types (although overall EE seems a better document management solution). Quickly done, no need to program and reinvent the wheel. A filtering menu can appear in a sidebar and a user can gradually filter through the results, e.g. perform a search for "widget", see results, then refine by documents published between a certain date, then refine by country, language, etc. And you can add/remove these fields very easily.

(3) Document import/export. For example, export the document to Word, PDF, etc. What makes Craft intriguing is that fields are entered in discrete, identifiable elements. For example, what if I wanted to export just document headers for a long document, it seems Craft can theoretically accomplish this easily because every header is a discrete field. It takes more work on the back end for data entry (but there is no perfect system.)

(4) Document Version System. Another issue would be to track revisions of the document as it moves along, e.g. first proposal. First revision. Second revision. Submission for approval. Document approved. -- Each of these documents are different versions of the same document. I've seen some extra data types which leads me to believe that the ability to generate a list of these documents as being related might be better suited with Craft - although I'm not familiar enough to be sure. Don't see EE/WP having a better solution, just manual fields that would require each document to be updated or a macro which inserts data each time a new revision is added.

Thank you all for any comments or thoughts.

If Craft is good enough for the AP, it'll be good enough for everyone. ;)
I have little experience with EE, other than migrating away from it, but I have built enough in WordPress so here's my experience with that, as compared to Craft.
Don't be afraid of the "coding" part. Twig is pretty easy to learn and you'll learn to love it. Throwing together a plugin is harder but with Craft's decent MVC structure, it'll be much more easier to maintain—more so than trying to get WordPress to bend to your will. Creating plugins that look and feel native are much much easier, since you're just extending Craft's already built-in stuff.
(1) Create relationships between docs
I'd go so far as to say this is Craft's most killer feature. Try to do this in WordPress, for example, and you end up throwing plugins at the problem or convoluted sql queries to get it to do what you want. ACF is great but Craft's engine is fast, built-in, and it works within all elements.  After you've used Craft's relations, it's hard to use something else.
Especially if you store actual documents, like PDFs or Word docs, assets are WordPress' achilles heel. By default, WP stores files in year/month directory structure—which makes sense for blogging but not for any kind of database.  Assets in Craft are first-class citizens, right down to the fact you can even add custom fields to them.
So, let's say you want to store the document you've copied from a Word doc. Why not store the original document as well? You can do that easily and if you ever have to refer back to the "archived original" it's just a relationship away. You could store that relationship either on the asset itself (refer back to the document) or on the entry that refers to the asset. Either way, Craft knows about it and you can use the relationship.
(2) Ajax based filtering system
My experience with WP plugins is hit and miss. They either will work as advertised or they won't. But that's it. Stray from that beaten path and you might as well be writing it yourself. This reddit thread (contains NSFW language, obviously it's reddit) has some good reasons why rolling your own can more productive in cases like this. Craft is so easy to query and add parameters to; AJAX is really just another layer. You need a solid base and WP is not going to cut it here. Craft's UI is so intuitive, it's an easy choice, especially when you have end users to support.
(3) Document import/export
Hard to say what you want to do as far as import—there's a whole cottage industry built on trying to parse Word and PDFs to html etc.—but when it comes to exporting out the data, like you mentioned, since Craft stores in discrete fields, you can get at just the data you need. You'd want to use something like ACF in WordPress but it's not as nice to query, especially when it comes to relationships. Having that built-in to Craft is a huge advantage.
(4) Document Version System
Craft has entry revisions built-in and it's one of the best implementations I've used. You can publish over current versions, have multiple drafts of the same document, name them, etc. To do this inside WordPress takes a fair amount of effort. The only thing WP has that Craft does not is a built-in diff viewer so you can see what changed. That's harder to do on a field-by-field basis. You'd also need to roll your own "publish status" in Craft though. WordPress has a slight leg up here but really, emphasis on slight.
What else?
Multiple languages built-in. Again, WP users love to throw plugins at this problem but it really needs to be built into a CMS' DNA. Craft Pro has this ready to go. Even if you don't buy the Pro version, Craft stores it in a future-friendly way, so when you are ready to go, you're not jumping through hoops. Brandon Kelly mentions this and he's absolutely right.


Direct access call for a twig template from a twig template gives 404 I'm trying to call for a Twig template _template from a Twig template, particularly from within AngularJS <script type="text/javascript"></scirpt> tags. A console log says, that the file was not found on the server with status of 404. Using {% include '' %} or {% embed '' %}interferes with AngularJS somehow. Does any way around exists to access that Twig template, without breaching the security?

Troubleshooting part of js:

$mdDialog.show({
  templateUrl: '_template',
})

Not sure exactly what you trying to do here?  Call a Twig template from Angular?

Twig is a server side technology, Angular is getting parsed on the client side. The only way Craft is going to parse a Twig template is when it encounters a URL.

Instead of calling the Twig template directly, you call the URL, which could match a template. Inside templates, make a folder like angular-views and then inside that put a file called md-dialog.twig.  From the front end, now you can call it from Angular like http://example.com/angular-views/md-dialog (the .twig is optional).

If you're trying to use Angular inside of a Twig template, you may want to use something like {% verbatim %} and then put your JS/Angular templating between those tags to make sure Twig doesn't touch any of it.


Permissions at field level. Can this be done? I have a public registration form process which assigns a specific group/permissions 'eventeer' to a user. This user can then login and can enter/edit information in a 'shared' section. 'Shared' meaning both admins + eventeer groups use the same admin cp section form.

Issue: I have one field that I dont want to expose to an 'eventeer' but only expose for admin. Can this be accomplished with craft v2.6+ and/or plugin?

Thanks in advance.

Not natively, but there's the Control Panel Body Classes plugin, which would enable you to add the handle for your "eventeers" User Group as a CSS classname to the <body> tag (i.e. body.usergroup-eventeers, if "eventeers" is the handle for your User Group).

With that classname in place, you could add some CSS to the Control Panel (easiest done w/ the CPCSS plugin) to hide the particular field, e.g. w/ something like the following:

body.usergroup-eventeers #fields-yourFieldHandle-field {
    display: none;
}

...or, if it makes sense, you could flip it around and have your field hidden by default, and visible only if the <body> has the .userlevel-admin classname - which would in effect hide the field from everybody except people w/ admin accounts:

#fields-yourFieldHandle-field {
    display: none;
}

body.userlevel-admin #fields-yourFieldHandle-field {
    display: block;
}

(Obviously, you'll need to change the yourFieldHandle part for the field's selector to your field's actual handle.)

In any case, keep in mind that this will not be a secure solution in the sense that the field will still be there, and any tech-savvy "eventeer" user can easily make the field appear by removing the above CSS rule in their browser's dev tools. However, in the current iteration of Craft it's as close as you'll come to accomplish what you want.


Linking to specific entries in Twig: How performant is Reference Tags parsing? I have a small menu of fixed entries that forms a sub-nav on a site.

I'm currently using Reference Tag parsing to grab links to these entries:

Help

Donate

About Us

I think this is a really clean/readable way to create this sub-nav, but I'm not sure about the performance implications. I could accomplish the same thing by calling up an ElementCriteriaModel using a fixedOrder:

{% entries = craft.entries.id(3666, 3667, 3668).fixedOrder(true) %}
{% for entry in entries %}

{{ entry.title }}

{% endfor %}

Does anybody know if one option is significantly performant over the other?

(I wouldn't be surprised if Craft is intelligently caching its entry data queries, such that it wouldn't have to create a new element query each time a Reference Tag is encountered/parsed... but I'm not knowledgable enough to say.)

Other SE questions about best-practice for linking to single entries:

What's the best way to link to an entry in a template?
How do I create a link to an entry using entry's id?

If you turn on debug mode in your config file, and then create an ultra simple template with just these code options in it, you should be able to look at the logs in the console. It should tell you the query time in milliseconds. I've never used reference tags; however, I  would suspect that the performance difference is minimal. I personally would opt for the second method, so that entry.title is not hard coded.

As a side note, you can also wrap the code in {% cache %}... {% endcache %} tags to further increase performance either way.


Route to User page from first segment I am building a site for a travel agency. Each agent needs to have his/her own public profile page. I want each agent's profile page to be accessed at agencyname.com/agentname, with agentname being the agent's username. This would load an agent profile template populated with the given agent's profile data.

I still need other non-agent segment-1 pages to continue working also, like agencyname.com/cruises or agencyname.com/group-travel. These would be 'normal' template pages.

Is there any way to make this work dynamically? Creating a dynamic route with only a token in Segment 1 breaks access to other regular pages. I don't want to have to create a hard route every time we add an agent, and we don't want to add another segment like agencyname.com/agent/agentname. We want the URL each agent puts on their business card to be as clean and easy to remember as possible.

I'm thinking something along the lines of this logic:

If Segment 1 matches a username
   Display the profile template for that user
Else
   Continue routing per the normal routing checks

I don't have the knowledge to build a plugin, or the budget for someone else to. I'm seeking solutions that could be implemented without a plugin (unless there's already a plugin available).

Any constructive thoughts are appreciated.

You could add a check at the top of all of your templates that tests if the first uri segment matches one the agent names.

{% set firstSegment = craft.request.firstSegment %}
{% set agents = craft.users.group('agents') %}
{% for agent in agents %}
    {% set agentName = agent.firstName ~ "-" ~ agent.lastName %}
    {% if firstSegment == agentName %}
        {% set requestedAgent = agent %}
    {% endif %}
{% endfor %}

{% if requestedAgent is defined %}
    {% include 'users/_profile' with { user: requestedAgent } only %}
{% else %}
    {% extend 'layouts/_main' %}

    ... normal page template goes here

{% endif %}

In your profile template you should now have a variable 'user' available with the requested agent.

{% block content %}

{% user.firstName %} {% user.lastName %}

...

{% endblock %}


Guest Entries creating new entry instead of editing the current one I am using the GuestEntries (https://github.com/pixelandtonic/GuestEntries) Plugin to try to allow guests to update entries. I have it working to where a guest can come to the page and fill out the form but unfortunately it is creating a new entry rather than editing the existing one.

I got it to work by adding the below at line 182 of GuestEntriesController.php

        $entry->id = craft()->request->getPost('entryId');

Then I added a hidden field with the current entries id in the template.

<input type="hidden" name="entryId" value="{{ entry.id }}">

I don't know if this is the best way to do it but it seems to be working. If this is going to cause issuees or there is a better way to do it let me know and I will swap my fix out with yours.


How can I tell if a field exists in a block of a matrix? I want to see if a certain field exists in a block of a matrix. Here is my code.

{% for block in entry.someStepContainer %}

    {% if block.type == "someStep" %}

{{loop.index}}

{{block.stepTitle}}

{{block.stepDescription}}

      <! -- this is part I'm trying to fix -->

      {% if block.stepAccordionContent %}

          {% for row in block.stepAccordionContent %}

{{row.accordionTitle}}

{{row.accordionContent}}

          {% endfor %}

      {% endif %}

    {% endif %}

{% endfor %}

I've tried using:

{% if block.stepAccordionContent | length %}

But this still yields an empty

stepAccordionContent is a table.

You can use {% if block.stepAccordionContent|length  %}...{% endif %} to test if any rows are defined in your table field.

Note: When you create a table field it will have an empty row defined under 'Default Values', which should be removed; otherwise all new instances of the table will have an empty row defined by default causing block.stepAccordionContent|length to return 1, instead of 0 as expected.


Delay Updating element slugs and URIs Job On a large website, after using feedme to import some content it immediatelly triggers the "Updating element slugs and URIs" process that takes very long time to complete. Is there a way to postpone or temporary disable this task and do the import first?

You can try disabling Craft's queue temporarily by adding 'runQueueAutomatically' => false to general.php, then trigger the feed via the command line.
Without testing this might prevent the 'Updating element slugs and URIs' job, but in any case – doing it this way you should see better performance overall.
p.s. if you add --verbose to the end of the command you can see what it's doing.