How to extend UserRecord? I'm writing a customer portal plugin that will have 3 types of users.

Organizations
Organization members
Private

I would like to use Craft's built in UserRecord for front end login, backend management, ..?, and extend it to handle these three user types.

The way I have it set up so far, is that I have a proxy user record, which handles the relations to the organization profile and user profile records. Below I have listed the relevant attributes/keys and relations for each of the records:

MyPortal_ProxyUserRecord:
Acts as a middle man between the Craft UserRecord and the two records further below.

id
craft_user_id
organization_id  (# | null if private user)
user_id  (# | null if organization)

'craft_user' => array(static::BELONGS_TO, 'UserRecord', 'craft_user_id'),
'organization_profile' => array(static::HAS_ONE, 'MyPortal_OrganizationProfileRecord', 'proxy_user_id'),
'user_profile' => array(static::HAS_ONE, 'MyPortal_UserProfileRecord', 'proxy_user_id'),

MyPortal_OrganizationProfileRecord:

id
proxy_user_id
contact_user_id

'proxy_user' => array(static::BELONGS_TO, 'MyPortal_ProxyUserRecord', 'proxy_user_id'),
// Organization members:
'user_profiles' => array(static::HAS_MANY, 'MyPortal_UserProfileRecord', 'organization_id'),
// Contact user:
'contact_user' => array(static::HAS_ONE, 'MyPortal_UserProfileRecord', 'organization_id'),

MyPortal_UserProfileRecord:
Handles both private users and organization members.

id
proxy_user_id
organization_id  (# | null if private user)

'proxy_user' => array(static::BELONGS_TO, 'MyPortal_ProxyUserRecord', 'proxy_user_id'),
'organization' => array(static::BELONGS_TO, 'MyPortal_OrganizationProfileRecord', 'organization_id'),

Questions:

Is it possible to extend the Craft UserRecord itself with the
necessary attributes and relations to handle the
OrganizationProfileRecord and the UserProfileRecord, and ditch the
proxy user record? If so, how do I do that?
If not possible, should I structure my records and relations differently than I have done so far?
Are there any pitfalls I should be vary of?

Please let me know if I should provide any further information! :)

Many thanks in advance for any help you can provide!  bowing

/Monkey

When extending Craft's active record classes (like UserRecord), you'll only be able to setup the AR relationships one way (from your class to Craft's i.e. MyPortal_ProxyUserRecord => UserRecord) as you've done.  Setting up the relationship in the other direction (UserRecord => MyPortal_ProxyUserRecord) would require hacking core Craft files (not recommended).

For queries going in that direction, you'd need to go outside the scope of AR and use QueryBuilder to manually build the SQL query you need.

As for your current structure, I'm not sure what the purpose of MyPortal_ProxyUserRecord is.  Why not just have MyPortal_UserProfileRecord and MyPortal_OrganizationProfileRecord link to UserRecord directly? Maybe you just want a single place for that interaction instead of two, I suppose.


Use loop index number in a Twig variable Let's say I have 5 Craft fields named "item1" thru "item5."

Instead of writing out each variable...

{{ entry.item1 }}
{{ entry.item2 }}
{{ entry.item3 }}
{{ entry.item4 }}
{{ entry.item5 }}

How can I create a loop to do this for me?

I've tried this...

{% for i is 1..5 %}

    {{ entry.item ~ loop.index }}

{% endfor %}

But it returns the error:

  Craft\EntryModel and its behaviors do not have a method or closure named "item".

I found the answer in the Twig documentation:
http://twig.sensiolabs.org/doc/templates.html#variables

  You can use a dot (.) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array), or the so-called "subscript" syntax ([]):

{{ foo.bar }}
{{ foo['bar'] }}

When using the subscript syntax, you can concatenate the loop.index like so:

{% for i is 1..5 %}

    {{ entry['item' ~ loop.index] }}

{% endfor %}

Or even simpler, use the i variable from the for loop.

{% for i is 1..5 %}

    {{ entry['item' ~ i] }}

{% endfor %}


Order matrix blocks by date field I'm using a matrix inside a Super Table to organize events, and I'd like to order the events using the date field for each event.

I'm currently showing the first five events using limit then using offset to show the rest of the blocks after the first five. Then I'm separating future and past events using the date field. Like this:

First five upcoming events:

{% for block in block.eventList.limit(5) %}
     {% if block.eventDate >= now %}
          {{ block.eventTitle }}
     {% endif %}
{% endfor %}

The rest of the upcoming events:

{% for block in block.eventList.offset(5) %}
     {% if block.eventDate >= now %}
          {{ block.eventTitle }}
     {% endif %}
{% endfor %}

All past events:

{% for block in block.eventList %}
     {% if block.eventDate <= now %}
          {{ block.eventTitle }}
     {% endif %}
{% endfor %}

This works fine as is, but it doesn't sort the events within the sections by the date field. How can I add that?

I hope I am not completely missing the point, but I guess like that:

Initial 5:

{% for block in block.eventList.eventDate('>=' ~ (now|atom)).orderBy('eventDate asc').limit(5).all() %}
     {{ block.eventTitle }}
{% endfor %}

rest:

{% for block in block.eventList.eventDate('>=' ~ (now|atom)).orderBy('eventDate asc').offset(5).all() %}
          {{ block.eventTitle }}
{% endfor %}

past events:

{% for block in block.eventList.eventDate('<' ~ (now|atom)).orderBy('eventDate desc').all() %}
     {{ block.eventTitle }}
{% endfor %}

you will probably need to change the date('Y-m-d') format


Is Redactor's default config saved as a .json file anywhere? When I need to make one tiny change to the default config it would be handy to be able to duplicate the current default.json file and just change a one thing instead of building a duplicate from scratch.

It's a small thing, but it would be a nice time saver. I've had no luck finding it, does anyone know if the default is saved somewhere?

As @Brandon said, the defaults are hardcoded in redactor.js so there isn't a default.json file, but if there was, this is what it would be (from Craft 2.3.2615):

{
    buttons: ['html', 'formatting', 'bold', 'italic', 'deleted',
    'unorderedlist', 'orderedlist', 'outdent', 'indent',
    'image', 'link', 'alignment', 'horizontalrule'],

    formatting: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5']
}

Since the above code could change on occasion consider checking directly over at the Redactor site:

Buttons defaults

Formatting defaults


Can’t run Craft CMS :( I'm getting the following message, when I try to access craft admin.
I have both the zip and unzip installed. Not sure why I'm getting this error.

MESSAGE:
Can’t run Craft CMS :(
Your server doesn’t meet the following requirements to run Craft CMS:
The zip extension is required for zip and unzip operations.
Please talk to your host/IT department about upgrading your server.

The error shows up because Craft can’t find the zip php extension.
Try to install it by running pecl install zip in your terminal.


Using the same title I have an article called Main Article and I am rolling out the chapters each week (8x). So, each chapter will have the MAIN Article Title AND Chapter Title.
eg: Stories from the top of the World; The Journey of the arborists

Stories from the top of the World; The way to the top
etc, etc...

I could create the MAIN Article as a single entry (with an excerpt) but this is not the brief from the client and use a relationship field to add the chapters to the Main Article Title.

I could add the Main Article title as a category and select this at each chapter entry, but how do I create the URL format to do this? This might also be tough to explain as a workflow for the client....

articles/{category}/{slug}

What else are the options?

You can set the URL format to be anything you want really, just setup your templates and then setup some routes; then it's all going to work automatic for your client and they never have to worry about it.


Register Assetbundle in frontend template How can I register an assetbundle in a frontend template?
This is my bundle

namespace secondred\formbuilder\assetbundles\Formbuilder;

use Craft;
use craft\web\AssetBundle;
use craft\web\assets\cp\CpAsset;

class FormbuilderAsset extends AssetBundle
{
    // Public Methods
    // =========================================================================

    /**
     * Initializes the bundle.
     */
    public function init()
    {
        // define the path that your publishable resources live
        $this->sourcePath = "@secondred/formbuilder/assetbundles/formbuilder/dist";

        // define the dependencies
        $this->depends = [
            CpAsset::class,
        ];

        // define the relative path to CSS/JS files that should be registered with the page
        // when this asset bundle is registered
        $this->js = [
            'js/Formbuilder.js',
        ];

        $this->css = [
            'css/Formbuilder.css',
        ];

        parent::init();
    }
}

And I can register it with in my controller without any problems
$this->view->registerAssetBundle(FormbuilderAsset::class);

But when I do

{% do view.registerAssetBundle("secondred\\formbuilder\\assetbundles\\formbuilder\\FormbuilderAsset") %}

nothing happens.. no request, no error, nothing in network tab and no html is added to the page

Update
I found the solution. If you are in a frontend ressource you need to call the {{ endBody() }} method in order to get the bundles

Answer:
In order to render all the scripts in your registered assetbundles you need to call this function

{{ endBody() }}

somewhere in your page (preferred at the end of the body)


Elements API - How to order / limit the output with an asset field of an entry I recently started using the Elements API and I made up a recipe site as an example project. It's pretty easy to output the recipes as json data.

But I now want some more control about the output of the data and only query a specific subset of the recipes. As long as I have the data needed for the selection directly in the recipes entries it's easy to filter or sort them accordingly. However sometimes I might want to manually pick and order entries. One solution would be to create extra attributes in the recipe entries, but this seems messy.

I would like to do that with an entry selection field since this seems to be the most intuitive option for content authors. My question is how can I use the data of an entry field to limit the output? My current solutions seem really bad:

I simply query each entry separately by id, but this seems like a terrible idea in particular for a larger selection.
I load all data and do the cleanup in Javascript. Even though the images at least wouldn't get loaded this way it seems like an increasingly bad idea with an increasing number of total entries.
The best solution for now seems to create an endpoint for the entry that contains the entry selection field and use the transformer to output the all the needed data - I miss the nice pagination / meta data that way however.

'transformer' => function(Entry $entry) {
     $selection =  [];
     foreach ($entry->selectedRecipes as $block) {
          $selection[] = [ array(
                          'title' => $block->title,
                          'id' => $block->id,
                          ...
                           )
                         ];
             }
     return [ 'recipes' => $selection,

This seems like a really basic problem and any hints on how to solve this problem are greatly appreciated.

Thank you

You could use the relatedTo parameter (docs) to query recipes related to the entry that has your Entries field on. Something like:

return [
    'elementType' => Entry::class,
    'criteria' => [
        'section' => 'recipes',
        'relatedTo' => ['sourceElement' => $entryWithEntriesField]
],

Where $entryWithEntriesField is the entry (or id of the entry) that contains the entry selection field would return the list of recipes attached to that entry.


Craft chokes on rendering large amounts of entries? So I have a section with 900 entries and I tried to just list them all on the page but Craft seems to choke after about 200 and will just not render any of them. Although I probably don't need to output all 900 it would be good to know what the issue is here?

You may need to up your php memory limit. Should be good through Host CP to do, or if locally, edit the php.ini file.

Also, craft will generally max out at 100 entries as default so adding .limit(null) to a request should also help...


Freeform Plugin: Success Page and Submission ID - Template not Found I am getting the following error when redirecting the form success message to a page. I am trying to pass in the submission ID...

HTTP 404 – Not Found – yii\web\NotFoundHttpException
Template not found: contact/success/5015

This is the Return URL

returnUrl: "{{ siteUrl }}contact/success/{{ submission.id }}",

I have set up a 'single' entry for the success page - do I need to somehow tie this in with the submission ID?

Did you set up a route and assign a template to it?

contact/success/{{ number }}


What is the most adviceable way to combine a staging and live database? Scenario:

Live server where customer adds content and articles, which are store
in the database
Staging server where we add new functionality, fields, sections and more

When the development of the new functionality on the staging server is complete, it should be merged with the new content of the live server.

How easy is this to handle? Is it as easy as just importing the staging db server into the live server one? Will not existing content be overwritten?

The way we do it is we take a copy of the live database when we begin development work, do the dev work on local/stage, get sign off... then manually add the new fields etc onto the live database. Otherwise, you're going to lose data.

I don't know of any way you could automagically merge two different databases.

One method to help speed up copying fields from one database to another (which is what you're doing) is to use the Field Manager plugin, which can export fields as JSON from your staging version, and you can import that JSON using Field Manager again on the live version. You'll still need to manually assign those fields to the associated sections.


Email template issue Craft Contact Form Extensions I am using Contact Form Extensions plugin https://github.com/Rias500/craft-contact-form-extensions for setting up custom notification email template but not sure what tag would be used for additional fields like Phone.
Here is my code sample:

Name: {{ submission.fromName }}

Company: {{ submission.Company }}

Name: {{ submission.fromEmail }}

Phone: {{ submission.Phone }}

Type of Enquiry: {{ submission.typeOfEnquiry }}

Message: {{ submission.message }}

Could anyone please help.

I think it should be:

{{ submission.message.Phone }}


Targeting entries in a structure In a structure like the following:

Offices             US          Albuquerque
[offices]                       Boston
                                Chicago
                                Denver

                    Mexico      Acapulco
                                Buenavista
                                Chihuahua

                    Canada      Ajax
                                Brampton

writing this code on the offices overview page

{% for entry in craft.entries.section('offices') %}

{{ entry.title }}

{% endfor %}

gives me an output of everything in the whole structure

when writing:

{% for entry in craft.entries.section('offices').level(1) %}

{{ entry.title }}

{% endfor %}

I get the title from the entry in the first level.

But how do i target a specific entry in the structure?
Let's say only Albuquerque, Chicago & Chihuahua?

I looked around but can't seem to find anything in the docs about that. Who can point me in the right direction?

To get a specific entry you need to know the id or slug of the entry. If the slug for Chicago is "chicago" (you find the slug in the side panel of the entry edit screen), you can get it like this:

{% set chicagoEntry = craft.entries.slug('chicago') %}

But hardcoding slugs and id's into templates is rarely a good idea. If you explain a bit more what you're trying to achieve, maybe we can provide a more helpful answer.

If you're trying to turn the structure into a menu of sorts, have a look at the documentation for the {% nav %} function, it was made specifically for this.


How do you setup CloudFront in P&T S3 plugin & how do you know if it works? I have the P&T Amazon S3 plugin.   It's connected to my S3 bucket.  It stores a few test .PDF files.   It is working.  I am able to access the files - and the URL is that of my S3 bucket - i.e., my-bucket-name.s3.amazonaws.com/filename.pdf

I created a CloudFront distribution.   It is deployed and enabled.

I added my CloudFront Distribution ID to the CloudFront Distribution ID field in the plugin.   Do I need to add the distribution's Domain Name to any of the plugin's settings?

How do I know if the image is being accessed through CloudFront?  The URL has not changed - i.e., - i.e., my-bucket-name.s3.amazonaws.com/filename.pdf

I can access the .PDFs in my S3 bucket using the CloudFront domain name -- i.e., cloud-front-domain-name.cloudfront.net/filename.pdf.

I wrote up an article that might be helpful for future-people looking for step by step instructions on setting this up: Setting Up AWS S3 Buckets + CloudFront CDN for your Assets


Unable to access login page or my website I have been unable to access my website or log into my CMS. I have checked with the server and everything is OK there but all I am getting is a blank page.

I updated craft manually following the instructions given.

I also have a staging site which I use for sharing with my client and this all works fine.

Is there anything I need to be checking? What will have stopped the website from working? I would really appreciate any help you can give with this.

Thanks in advance.

One small detail that can cause the front-end and back-end of your site to result in a blank white page, is if you have a syntax error in your general.php file, such as a missing comma at the end of a line.  If you've just made a recent edit to your config files, take a closer look at them and make sure that you don't have any small errors.

For example, the following multi-environment config is missing a comma at the end of the omitScriptNameInUrls setting, and that minor detail would make both the front-end and back-end of a site result in a blank white page:

return array(
    '*' => array(
        'omitScriptNameInUrls' => true
        'devMode' => false
    )
);


Fetch pending entries with GraphQL I'm setting up Craft to be used headlessly with a mobile app, and content will be created several days before it is published. I want app admins to be able to see upcoming/pending entries. Is there a way to fetch all entries, not just currently published ones? When I do basic queries with the GraphQL api explorer I only see entries that are past their post date, but I'm a GraphQL newbie, so maybe I'm missing something?

If you want live and pending entries, you would need to pass status to your query with the values you want (docs).
query yourQuery {
  entries(section: "yourSectionHandle", status: ["live", "pending"]) {
    title
  }
}

Or if you want to use variables:
query yourQuery($section: [String], $status: [String]) {
  entries(section: $section, status: $status) {
    title
  }
}

# query variables:
{
  "section": "yourSectionHandle",
  "status": ["live", "pending"]
}

If you want all entries, (disabled and expired included) you can use status:null.


Account verification error I have created a new account and attempted to verify the account by clicking the activation link in the verification email.  On doing so I get the following error.

Bad Request
Param “id” doesn’t exist.

Any ideas how I can resolve this issue.

I am running the latest version of Craft.

I have replicated the issue locally and on our staging server.

Thanks in advance

I don't recall the specific version/build and my search-fu is weak today, but this was a bug in Craft that should have been fixed in a semi-recent build.  Try updating to the latest and see if you still have the issue.

Update:

Every time we've been able to investigate this issue so far, it has been because of either .htaccess stripping querystring params behind the scenes (i.e. no [QSA] flag on the rewrite rule), or the equivalent in nginx-land.


Only show entries related to category I am trying to create a category template that shows all entries to show relating to the categories.

At the minute the cats are

Industry
Chemical
Medical

Personally I would set the category select field outside of the matrix block but that's up to you.
The problem you are running in to at the moment is you are not looping over the matrix field.

{% for entry in craft.entries.section('job') %}
    {% for block in entry.matrixFieldName if block.type == 'job' %}
        {% for category in block.category %}

{{category.title}}

        {% endfor %}
        {{ block.title }}

    {% endfor %}
{% endfor %}

So what we are doing here in the first loop we dive into the jobs section.

{% for entry in craft.entries.section('job') %}

Once we are inside a job entry we loop over the matrix field containing the "job" block. We only want to display the "job" block (security for when you add more blocks in the future).

{% for block in entry.matrixFieldName if block.type == 'job' %}

Once we get into the matrix field we loop over the selected category field. This way you get access to all the fields inside that category (including the title).

{% for category in block.category %}

Now you have access to all the fields.
All the fields you want to use from the jobs entry you can grab by {{ entry.field }}. All the fields inside the matrix block by {{ block.field }}. And everything inside the category by {{ category.field }}.

OLD ANSWER

Correct me if I get you wrong.

I guess you have a field that connects an entry to a category but what you could try is something like this:

{% for entry in craft.entries.section('jobs') %}
    {% for category in entry.CATEGORYFIELD %}

{{category.title}}

    {% endfor %}
     {{entry.title}}

{% endfor %}

This is if the order doesn't matter.


Local install does not start, PDO Exception I wanted to install a single instance of craft on my local machine. However upon starting the installation via calling /admin/ or /admin/install, the only message I get, is

  SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
  The SQL being executed was: SHOW TABLES LIKE 'craft_%'

Which in itself is weird, since I have modified the configuration already to not use craft_ as a table prefix.

These are my settings:

OS: Mac OS X 10.11.3 (El Capitan)
PHP 5.6.25
MySQL 5.7.14
Apache 2.4.16
Latest Craft 2 build from today / Latest Craft 3 build from today

I have made the following changes to the configuration:

craft/config/db.php:

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

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

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

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

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

craft/config/general.php:

return [
    '.local' => [
        'devMode' => true,
    ],
    '*' => [
        'omitScriptNameInUrls' => true,
    ],
];

I even went the extra mile and updated the my.cnf for mysql in order to work properly in 5.7:

[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Any suggestions?

Edit Since the mods removed the craft3 tag due to my typo, I thought it was necessary to say that this error occurs on both the latest version of craft3 and craft2.

You are using multi-environment configs improperly.

You must have an environment with the * key. This is how Craft knows that you are using a multi-environment config. Even if the value is simply an empty array, it must exist.

  The '*' array is required to enable Craft’s multi-environment config support, even if you don’t need it. Craft specifically checks for it when deciding whether to enable multi-environment config support or not.

And this is a bit of speculation... but I'd highly recommend having your * environment as the first item in the array. I'm not sure if it makes a difference to Craft, but it's at least a bit of a standard.


How to filter entries by slug in url segment? I want to return entries in the news section, except the one that has a slug the matches url segment 2.

I've tried:

{% for entry in craft.entries.section('news').slug(not craft.request.getSegment(2)).limit(6) %}...
{% for entry in craft.entries.section('news').slug('and, not craft.request.getSegment(2)').limit(6) %}...

But neither work - all entries are returned.

What's the right syntax please?

I think there is just some confusion between what should be a string or not. From the docs on Parameter Value Syntax:

  To exclude entries with a given value, you must pass in a string, prefixed with not

To that end the following should work for your example:

{% for entry in craft.entries.section('news').slug('not ' ~ craft.request.getSegment(2)).limit(6) %}...


How can I join plugin data with entry data based on uri? I have a plugin with a record (and model). The record have attributes uri and hits. The uri attribute in my record corresponds to an entry's uri, as stored in the craft_elements_i18n table.

What is the most efficient way to return entries with the uris I have stored, sorted on hits? Is there a way to join the uri attribute in my record with the uri in the craft_elements_i18n table, and return entry data and hits in one go?

Right now I have this, which does the job but isn't very efficient:

$results = $this->queryResultRecord->getQueryResultsBySetId($querySet->id);

if ($results) {
    foreach ($results as $result) {
        $criteria = craft()->elements->getCriteria(ElementType::Entry);
        $criteria->uri = $result->uri;
        $entries = $criteria->find();

        if ($entries) {
            $entry = $entries[0];
            $return[] = array('entry'=>$entry, 'hits'=>$result->hits);
        }
    }
}

The getQueryResultsBySetId method return the data from my record sorted by hits. The $return variable is returned back to my frontend templates where I can do:

{% for result in results %}
    {{ result.entry.title }} - {{ result.hits }}<br>
{% endfor %}

You could of course manually create a select query with a join that fetches entries ordered by hits descending, however you will basically be recreating what $criteria->find() does above. I imagine this will introduce an almost negligible performance improvement, but it really depends on how many entries you are returning.

The following code should give you a starting point:

$query = craft()->db->createCommand()
    ->from('pluginTable pluginTable')
    ->join('elements_i18n elements_i18n', 'elements_i18n.uri = pluginTable.uri')
    ->join(...)
    ->order('pluginTable.hits desc');


Craft 2: Is there a hook for Craft Commerce Orders admin page? My plugin is sort of an extension for the Craft Commerce, where I need to provide custom data on the craft commerce orders page.
So I'm wondering is there a way to listen for an event, which fires when an admin navigates to the Orders page?
Thanks.

Ok, I got a solution. In my plugin's init function I've done the following hook:

craft()->templates->hook('cp.commerce.order.edit.main-pane', function (&$context) { ... }

If there is more 'elegant' solution, please shoot.
Cheers.


Outputting Matrix Loop in Template I have looked at documentation and I still can't figure out how to output the matrix to my template.

The Field handle name is: threeHomepageImages

The Block type handle name is: images

The Fields names are: image, alt, and imageTitle

I have the following and tried a few combinations, but no luck. Any help is much appreciated.

{% for block in entry.threeHomepageImages.type('images') %}
    {{ image }} {{ alt }} {{ imageTitle }}
{% endfor %}

You're almost there.

Every block returns a MatrixBlockModel, so you have to reference your block when getting the attributes:

{% for block in entry.threeHomepageImages.type('images') %}

{{ block.imageTitle }}

    {# Save images to variable for reuse #}
    {% set image = block.image %}
    {# Check if there is any images #}
    {% if image | length %}
        {# Get url #}
        {% set image = image.first().getUrl() %}

    {% endif %}
{% endfor %}


No Add New Entry button I'm just a beginner in Craft CMS but i'm wondering why there's no Add New Entry button in my dashboard. What should be the problem with it?

There is a Quick Post widget that allows you to create entries from the Dashboard page of the Control Panel.

A New Entry button is available from the entries index pages located at the top right, e.g. http://
example.com/admin/entries/news


Setting valueless boolean attributes with the tag function When using the tag function, how does one handle valueless attributes which could also be null?
For example, it's great we can do…
{% set idVar   = 'idstring' %}
{% set nameVar = 'namestring' %}
{% set typeVar = 'typestring' %}

{{ tag('input', {
    id: idVar,
    name: nameVar,
    type: typeVar
}) }}

…to generate:
<input id="idstring" name="namestring" type="typestring">

But what about if the required attribute is also a variable? We can’t do:
{% set reqVar  = '' %}

{% if field is required %}
    {% set reqVar = 'required' %}
{% endif %}

{{ tag('input', {
    id: idVar,
    name: nameVar,
    required: reqVar
}) }}

…because if reqVar is empty, one would want the required attribute to not be written at all. To generate:
<input id="idstring" name="namestring" type="typestring">

…and not:
<input id="idstring" name="namestring" type="typestring" required>

The same thing applies to other boolean attributes like hidden.
Is there a way to do this with this function? What am I missing or not getting?

If an attribute is set to true, it will get added without a value.
{{ tag('input', {
    id: idVar,
    name: nameVar,
    required: true
}) }}

Also, if it is set to null or false, it will be omitted, as if it was never listed in the first place.


Digital Ocean: Dev + Production Droplets I've been learning craft and want to setup a production & development environment. I've primary HTML CSS experience with limited backend or server related experience

One way I thought about doing this was setting up 2 separate droplets on Digital Ocean (w/ServerPilot) and copying digital ocean snapshots from the dev droplet to the production droplet.

Is this a feasible approach?
Does the license allow this if I don't map a domain to it and operate it as an IP address OR use an obscure term (staging etc.) in a odd domain (vs. sub-domain as mentioned in docs)?
Is there a better (noob-friendly, learnable) way to do this?

Thanks

Does the license allow this if I don't map a domain to it and operate it as an IP address OR use an obscure term (staging etc.) in a odd domain (vs. sub-domain as mentioned in docs)?

Yes. As far as I'm aware, Pixel & Tonic consider a development site to be any non public domain.

  Is this a feasible approach?
  Is there a better (noob-friendly, learnable) way to do this?

Lumping these 2 together since they're directly related.  This question and subsequent answers  might help you out as well as Craft's own list of resources.

It really depends on what you want to learn. When you spin up a droplet or other virtual machine, there's a lot of moving parts there. You'll be dealing with a lot of server management and not necessarily Craft development. It's easy to go really deep down the rabbit role and come out with a lot of (depending on what you seek out) useless knowledge. If you're just tinkering around, you probably want it as hands-off as possible.

Instead of paying for 2 droplet instances, you could spin up a virtual machine locally, like Virtualbox or something prebuilt like Laravel's Homestead. A droplet is also on the internet, thus a "public" server, so unless you want people hacking your instance, you'll want to secure it down. That just adds another layer of complexity.

Virtual machines are great solutions but they're also overkill usually. I find the easiest approach is to develop locally and use something like MAMP and then push it to staging and/or production servers. You don't need to worry much about the nitty gritty of permissions, firewalls, etc.


Craft redirects to domain.tld/domain.tld/ on logout I have a logout button on my site that points to the logoutUrl.

While the logout works and ends the user session, the user is brought to a page with the URL similar to domain.tld/domain.tld/ where domain.tld is my test-server's domain.

Naturally, this results in a 404 since I don't have a template to render a matching URL.

Any idea how to fix this or what could be causing it?

Thanks!

So after a bit of trial an error, setting a protocol for the siteUrl in config/general.php fixed it!

Ex. I had 'siteUrl' => 'domain.tld' so I changed it to 'siteUrl' => '//domain.tld' and all is well.


Sending Error Message to Template With No Logged In User - Craft 2 I'm working at getting error messages sent from my plugin to my template (on the front end), when there is no session (no logged in user).
The plugin is for LDAP authentication.

Edit: For clarification, this plugin (and the error messages) will be for as-of-yet un-logged-in users.  Would a session structure be the only way to get the messages to those end users?

I've tried this (below), but I get the error message (below):

code in the plugin controller:   craft()->userSession->setFlash('msg_template',"Credentials were not accepted.")

code in the template:

{% set message = craft.app.session.getFlash('msg_template') %}

{% if message|length > 0 %}
{{message}}
{% endif %}

error message:

Neither the property "session" nor one of the methods "session()", "getsession()"/"issession()" or "__call()" exist and have public access in class "Craft\AppVariable

You are mixing Craft 3 code with Craft 2. There is no native way to access the session in Craft 2 via Twig so you need to inject the functions with your plugin

See a working example here


Display entries that belong to a category I have a page that should show entries within a category, and then entries within children of that category. Basically, I need a way to loop through entries that have a level 1 category but not a level 2 category.

To give an example, suppose I've got some categories set up like this:

1.

— 1.1.

—— 1.1.1.

— 1.2.

2.

There's also one entry related to each category. I'd then use code like this:

{# Reference the category #}
{% set cat = craft.categories.title('1.').first() %}

{# Find related entries #}
{% set entries = craft.entries.section('mySection').relatedTo(cat).find() %}

{# Print them out #}
{% for entry in entries %}
    <p>{{ entry.title }}</p>
{% endfor %}

This would output:

1.

1.1.

1.1.1.

1.2.

How can I find entries which are directly related to the category “1.”?

Categories are Craft's implementation of a taxonomy, which itself is the classification of things into groups and sub-groups. In this respect, I suppose it makes sense that if an entry is related to a sub-category, it inherits (it's also related to) its parent. That would explain why you're getting all entries in this way.

At the moment, the only way I can think of is to test what level the category/sub-category is.

Something like this would get you started for the time being. I don't really like this because it seems convoluted, so I'll put my thinking cap on and I may revise.

{% set category = craft.categories.group('myGroup').title('1.').first() %}
{% set entries = craft.entries.section('mySection').relatedTo(category).find() %}
{% set isThisLevel = false %}
{% for entry in entries %}

    {# Test if this entry is related to the correct category level #}
    {% for relatedCat in entry.catField %}
        {% if relatedCat.level == category.level %}
            {% set isThisLevel = true %}
        {% endif %}
    {% endfor %}

    {# Only output if it's this category level #}
    {% if isThisLevel %}
        {# Do whatever you want #}
    {% endif %}

{% endfor %}


Craft cacheMethod setting is being overridden I am trying to setup Craft to use a memcached (yes it is memcached, not memcache) cluster in AWS ElastiCache to handle sessions. I originally went the route of updating my php.ini file in Apache2 to override the PHP session save handler and session save path. That worked at first, but I found that sometimes memcached would seem to return null if a session object was being accessed around the same time. After running into that error a bunch and not being able to resolve it, I decided to try setting up memcached through Craft.

My question is does Craft default to local file storage if it can't connect to my memcached cluster? The reason I think this is happening is because if I use the overridePhpSessionLocation, I can tell that it isn't working because I am getting timed out on my site since we store the timeout in the session. However, when I set overridePhpSessionLocation to 'auto', and then put all the proper information in my memcache.php file, the site seems to work. But if I screw up the hostname in the memcache.php file, the site still works. So what is going on? Is Craft defaulting to local file storage when there is a connection issue or is there something else happening?

The craft/config/memcache.php file has nothing to do with where PHP sessions are stored.  It is for Craft's general purpose data caching.

If you want to save PHP session in memcache, you'll need to set the php.ini save_handler and save_path similar to: https://www.digitalocean.com/community/tutorials/how-to-store-php-sessions-in-memcached-on-a-centos-vps

At this point, I'd suggest not using the overridePhpSessionLocation config setting.  Everything it does can be done through php.ini and it's been removed from the upcoming Craft 3 release anyway.


Is it possible to reorder globals in the back end? Right now Globals are listed in alpha order in the back end.

I was wondering if it would be possible to reorder them somehow? Maybe when working under Settings > Globals, etc.?

It's currently not possible to change the order in the control panel, but we might look into that for a future release.  They are currently set to display alphabetically.


How can I troubleshoot why my queue of tasks in stuck in Craft 3? I have a series of tasks lined up in the queue to run but they are just marking one as in progress and then sitting there and not executing.

I have tried updating the DB table "queue" by doing the following:

1) Changing the failed field to 1 and dateFailed to NOW() thus marking the task as failed then clicking the retry option. This just puts the task back into the same routine.

2) Changing both dateReserved and timeUpdated to NULL thus resetting the task and it go back into pending but this also doesn't help.

I'm trying to debug the cause of this but getting lost in the code as it seems the QueueController is setting everything as it should be but then either not getting a response and updating the progress or it's failing silently somewhere along the way.

I have attached my queue logs below for reference but I can't see anything unless I am missing something glaringly obvious!?

I asked on the #craft3 Slack channel and got some help but nothing worked. Hopefully, we can find a solution on here and share with others.

CP Screenshot

Database Screenshot

Queue.log

I typically just truncate (delete all of the rows) the queue table if something goes wrong with a task.

Then I delete all of the files in storage/logs/ and I try to reproduce the problem. If it still happens, then I look in queue.log and web.log to see what the issue is.

Usually searching on [error] finds what I'm looking for pretty easily. Occasionally I have to browse through the file to find the actual problem, but that's why I delete the log files before I do it, so there isn't as much to wade through.

Relevant articles I wrote since this answer:

Robust queue job handling in Craft CMS
Zen and the Art of Craft CMS Log File Reading


Admin and Dashboard showing 404 I am deploying a Craft site, I have it installed and everything is working fine, but whenever I try to access the admin panel I get a generic 404. I have tried every solution offered in similar questions, none of them work.
Here's my .htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On

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

And my Apache Virtual Host file:

<VirtualHost *:80>
        ServerAdmin info@servername.com
    ServerName servername.com
    ServerAlias www.servername.com
        DocumentRoot /var/www/servername.com/public_html/web/

        <Directory /var/www/servername.com/>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
        </Directory>

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

        <IfModule mod_dir.c>
            DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
        </IfModule>

</VirtualHost>

Making the url hostname/index.php/admin does work, however.
Any suggestions would be much appreciated, or if more information is required please let me know.

In my case, my url routing wasn't functional because the mod_rewrite module in Apache was disabled. I enabled it with a2enmod, restarted Apache, and my problem was solved.


How to limit selected items that appear on special page I have a client that wants to select "featured" entries to appear on their home page, and in a specific order that they can set and change. My initial idea was to set up a featured check box and just search for that, but I need to limit the possible number of total entries selected to 5.

The entires come from multiple sections so I cannot just limit one section, and I need to limit how many they can select on the backend, not just how many appear in the view (that I can do).

right now the set up is with the featured checkbox, but the problem is they can just keep checking boxes and if they do not uncheck another one it will not have the expected behavior.

Just add an Entries field to the home page Single and limit it to 5? That also allows designated users to decide what appears on the home page.


How would you show a specific entry 'and' its children I'm creating a footer menu and want to show an entry id and its children, atm I'm just getting the descendants but struggling to show the parent and children as well

        {% set entries = craft.entries.section('pages').descendantOf(8) %}

{{ entry.parent }}

        {% nav entry in entries %}

{{ entry.title }}

            {% ifchildren %}

                {% children %}

            {% endifchildren %}

        {% endnav %}

Appreciate this is the wrong approach any feedback appreciated on how to display the title of id 8 as well as its children, atm parent.entry is not showing

Try merging like this

{% set parent = craft.entries.section('pages').id(8) %}

{% set entries = craft.entries.section('pages').descendantOf(8).limit(1) %}

{% set entries = parent|merge(entries) %}

{% for entry in entries.all() %}
  output your entries here
{% endfor %}


Autogenerated PDF Thumbnail using PDFThumb in a Matrix Field I would like to autogenerate a thumbnail of PDF's, and from this question I found the plugin PDFThumb. The problem I'm running into is I'm relatively new to Craft, and I can't seem to figure out how to use the provided code when it is with a Matrix field.
As I said I'm new to this, and I usually end up tying myself in knots when trying to backtrack the variable references, and I think that's the problem here.
The reference code from the plugin repo:
{% for myAsset in item.assetRef %}

{% endfor %}

And my code:
{% set pdfBlocks = entry.infoPagePDF.all() %}
{% if pdfBlocks|length %}
        {% for block in pdfBlocks %}
            {% if block.type == "pdf" %}
                {% if block.pdfFile %}
                    {% set rel = block.pdfFile.one() %}
                    {% if rel %}
                        {{ rel.title }}
                    {# Autogenerated Thumb #}
                        {% for myAsset in item.assetRef %}

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

The link generates fine, it's the image that doesn't.
I've tried a bunch of different variations, but the problem (I think) revolves around the fact I'm not sure what I'm supposed to be referencing in the FOR(myAsset and item.assetRef), so for clarity I reset my attempts to the provided code example.

You mixed in some code from the documentation resulting in a wrong variable name..
{% set pdfBlocks = entry.inhaltMatrix.all() %}
    {% if pdfBlocks|length %}
        {% for block in pdfBlocks %}
            {% if block.type == "pdf" %}
                {% if block.pdfFile %}
                    {% set rel = block.pdfFile.one() %}
                    {% if rel %}
                        {{ rel.title }}

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

Also be sure to go to the plugins settings and set the appropriate assets paths.


Live Preview: Hide tabs from live preview I've noticed that Live Preview mode includes fields from all tabs. Is it possible to specify tabs to be left out of the Live Preview display?

For example, if you have an 'SEO' tab which consists of meta data it's not relevant to include this in the Live Preview mode whilst constructing the page. With lots of tabs this just becomes confusing for the user when only a few of them are relevant.

Is there a way to exclude set tabs or fields?

There is currently no out-of-the-box way to do that.

You might be able to pull it off with something like the CP-CSS plugin, but I'm not sure how you'd just target the tab when the Live Preview pane is open.

Otherwise, you can always make a feature request!


How to make field instructions show as tooltip? How to turn

show as the following style

Install control panel CSS plugin, and add the following style.
.field .heading{
  position: relative;
}

.field.tooltip-icon-append label:after{
    content: "i";
    font-style: italic;
    font-family: open-sans;
    display: inline-block;
    position: relative!important;
    top: 0!important;
    left: 0!important;
    color: #fff;
    width: 17px;
    height: 17px;
    margin-top: 0;
    margin-left: 5px!important;
    line-height: 17px;
    font-size: 13px;
    background-color: rgba(0,135,255,.7);
    border-radius: 50%;
    text-align: center;
    opacity: 1;
    -webkit-font-smoothing: auto;
}

.field .heading .instructions {
    visibility: hidden;
    max-width: 100vw;
    background-color: #ddd;
    color: #000;
    border-radius: 6px;
    padding: 10px;
    position: absolute;
    z-index: 1000;
    bottom: 150%;
    width: 300px;
    opacity: 0;
    box-shadow: 0 0 0 1px rgba(205,216,228,.25), 0 2px 12px rgba(205,216,228,.5);
    transition: opacity .3s;
}

.field .instructions::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 25px;
    border-width: 10px;
    border-style: solid;
    border-color: #ddd transparent transparent;
}

.field .heading:hover .instructions {
  visibility: visible;
  opacity: 1;
}

Install control panel JS plugin and add the following code.
    $(".field>.heading").each(function(){
        var instruction = $(this).find(".instructions");
        if(instruction.length !== 0){
            $(this).parent().addClass("tooltip-icon-append");
        }
    });


For loop does not display all entries in section I have a for loop for all entries.  There is no limit set, yet the loop is not displaying all the entries.  The missing entries are the oldest.  These missing entries do appear on category specific pages.

There are no errors.  I have approximately 100 entries.  The for loop is only displaying the most recent 80 or so.

Any ideas?
Thanks

{% for post in craft.entries.section('posts') %}
                {% if loop.first and craft.request.pageNum == 1 %}

                                {{post.title}}{{post.tagline}}

                {% else %}

                                {{post.title}}

                {% endif %}
                {% endfor %}

Craft has a default limit of a 100 elements returned via an ElementCriteriaModel. To pull all elements, you'll need to explicitly set limit to null:

{% for post in craft.entries.section('posts').limit(null) %}
    ...
{% endfor %}


Return json formatted entries and include a header for Access-Control-Allow-Origin Hi Not sure on the best way to do this. I have some javascript that requires a json formatted file to populate a calendar. I can do this in php by adding the following to the file that is being requested:

header('Access-Control-Allow-Origin: *');
    $array = array(
    array('date' => "27/9/2015", 'title' => 'BBC Event', 'link' => 'http://www.bbc.co.uk')
    );
echo json_encode($array);

I need to be able to do the same with craft. I have tried just formatting the entries in twig which returns the json as it should be but because the header is missing the javascript call does not run it. I have also created a small plugin to pull out all the entries which may be a better option. I just need to know how to return those entries in json to a template as per the above php would create with a header included.

Any help much appreciated.

Cheers

You can set the header in Twig with the {% header %} function. Like this:

{% header "Content-Type: application/json; charset=utf-8" %}
{% header "Access-Control-Allow-Origin: *" %}

As to generating the actual json, my favourite is using the prune plugin and do it like this:

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

{
    {%- spaceless -%}
    "myEntries": {{ myEntries | prune(['onefield', 'anotherfield']) | json_encode() | raw }},
    {%- endspaceless -%}
}

You could also just loop over all the entries and create the json yourself, but I always get into all sorts of issues with encoding when doing that.

If you're going to do a lot of json requests, you could also look into the Element API plugin from Pixel & Tonic. You'd probably have to set the headers on the webserver level (.htaccess or nginx.conf) though.


Is there a native function or plugin to allow admins to email all users? I want to be able to provide the admin with a function so that they can email all registered users of the site.

Is there a native function or plugin that would make this possible?

Currently there isn't a native function to do this.

The only plugin that I know of that can do this, is Sprout Email from Barrel Strength Design.

EDIT:

I just released a plugin called Craft-Mailer which does what you are looking for.


Craft Search looking for keywords contained in the query Edited for clarity:

I do have a search form in the frontend where customers can enter keywords.
The way it searches now only returns exact matches. I'd like to tell Craft to look for works containing the keyword the look for.

I know I have to set the 'q' param to do this but I have no idea what I should do.

Search for results page:

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search(query).section('oeuvres').order('score') %}

From the docs:

{% set results = craft.entries.search('*' ~ query ~ '*').order('score') %}


Page breaks when editing a field I'm suddenly having issues with multiple Craft builds on my local dev environment.

Basically, everything else is working fine but when I edit a field the page breaks. It appears to only be displaying the form with any html, head or body tags. I installed a fresh copy and the issue also occurs on that build. I'm thinking it could be an issue with my version of MAMP or perhaps it's a known issue. Any ideas?

Looks like PHP is running out of memory.  You can edit your php.ini file's memory_limit setting to something higher than 32M, which is probably what it's set to right now.  Bump it up to 64M or 128M and restart Apache and you should be set.


Shortlist plugin error when creating a new list I'm getting this error when I try create a new list:

CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 1364 Field 'userSlug' doesn't have a default value. The SQL statement executed was: INSERT INTO `craft_shortlist_list` (`default`, `public`, `type`, `ownerType`, `uid`, `ownerId`, `id`, `dateUpdated`, `dateCreated`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7, :yp8). Bound with :yp0=0, :yp1=1, :yp2='manual', :yp3='member', :yp4='8fb7840a-a399-4eb3-bdf7-c59cb656bbff', :yp5='1', :yp6=1698, :yp7='2017-04-24 09:11:47', :yp8='2017-04-24 09:11:47'

Some help would be greatly appreciated!

I think you're using an older version of the plugin.

That bug was definitely fixed in the current version - which is actually 1.0.4 - although oddly that is not available as a 'public release' it seems.

I'd contact Joel and get him to update his version page! http://squarebit.co.uk/contact


Migrating a whole website between Craft instances A developer built our site locally configured as "craft.dev". At the same time, my sysadmin was busy getting Craft installed with Apache on our Linux server. He set that up with our real domain and purchased the $299 license for "ourcoolwebsite.com".

Now we've got the real website on the developer's machine, and a blank website on the linux server.

What files/folders do we need to migrate to get the real website up? Should we just dump and load his database and overwrite the one that was created for the install? I am guessing there are some database tables with data specific to my purchase and license key that differ from his. Basically I want to know how to take his work and put it into my production environment with database tables and file paths.

Make sure both Craft installs are up-to-date.
Craft's license is saved in craft/config/license.key, make a backup of your purchased license file.
Move all your files/directories except:

  /craft/app/
  /craft/storage/

Copy the backup of your license.key to craft/config/.
Remove /craft/storage/, if it exists on your new server, to prevent cache errors.
"dump and load" your database to the new server. Craft will update what's necessary.
Update your config settings in /craft/config/.
Go to your BackEnd.

Also you might find this interesting:

What's the best practice for handling data migration and organization across development environments?


How to reference an entry field in a guest user form? I'm new to Craft.  I've been trying to wrap my head around how to design the concept of Events and Event Registrations.  Currently I have both Events and Event Registrations as their own Sections as Channels.  An Event Registration has an Entry field to tie it back to an Event.  Our admins will create an Event, but we want the public to be able to register for an event via a form.  I'm using the guest-entries plugin and am very close to getting this all tied together, but am unsure how to pass the reference to the Event in the form.

I can pass it in via the url http://example.demo/register.html?eventId=99

But what do I reference so that the correct info will be sent to identify the Event entry when the form is submitted?

I assume I can send it via a hidden field, but am not sure what value to send:

    {% set eventId = craft.request.getParam('eventId') %}
    <input type="hidden" name="fields[event]" value="{{ eventId }}">

OR

If anyone sees a better way to design this, I would be open to other ideas.

So, I found the answer after much digging.

Thanks to this answer https://craftcms.stackexchange.com/a/9831/7962

I see that the entries field type has to be referenced with an additional set of brackets.  My form now works after changing my input to:

<input type="hidden" name="fields[event][]" value="{{ eventId }}">


Is there a way to upload an asset with a URL? I'm at the data entry stage of development and I've got a slew of entries with images to create. I'm stepping through the process manually and I'd like to use the URL of the image in the Upload files dialog instead of doing the download/upload rigamarole.

The images are on a server I don't have access to outside of their website. Ideally I would use the image URL in the Upload files dialog box instead of a local path and the image would be fetched and saved as an asset associated with the entry.

If this workflow seems parochial alternative solutions are welcome!

Firstly, you could manually copy/paste all your images into your Asset Source folders, then hit "Update Asset Indexes" from the settings. What this does is scan the directories for files, and creates them in the database if they don't exist. Once thats done, in your entries, you simply need to enter the filename in the search field (once you click "Add an Asset" on your asset field), and you're done.

For a more automated solution, you could look at Feed Me to update your entries, along with automatically uploading your assets from a provided URL. Your feed could be as simple as:

[{
  title: "Entry Title 1"
  images: [
    "http://my.website/my-image-1.jpg",
    "http://my.website/my-image-2.jpg"
  ]
}, {
  title: "Entry Title 2"
  images: [
    "http://my.website/my-image-3.jpg",
    "http://my.website/my-image-4.jpg"
  ]
}]


How do you create dynamic error pages? I want to have one template handle all of my error pages (instead of creating 404.html, 500.html, &c.).

A big thanks to Michael Rog (@rog) for the answer on Slack. You can create a catch-all error template with the name error (using whatever file ext works for you). That template also has access to a variable called code that tells you what kind of error it is. In my case, I'm using it to display HTTP Cats.


Asset dynamic subfolder for User Matrix I need to set an asset field's dynamic subfolder path to the User ID.

The field is within a matrix.

The matrix a field in a User profile.

Setting it to {currentUser.id}, {owner.author.id}, {object.author.id} results in an invalid path message when trying to upload to the asset field.

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

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


Plot absolute coordinates / Image map I have a site where I want to set up a "tour" of a software screenshot, and I need to allow users to select points on an image to insert the tour "stops". Is there an add-on like DevDemon's Entry Mapper for Craft? Or does anyone have a suggestion for a way to do this that doesn't involve explaining to a client how to figure out coordinates on an image and then entering them into a Matrix field?

Have a look at Iain Urquhart's plugin, Pointy: https://github.com/iainurquhart/Craft-Pointy

It's a port of his EE addon that's similar to Entry Mapper, but I'm not 100% certain if it's production ready or not.


Installing Craft in a Sub Folder I have created a Craft CMS site on a VPS Server running CentOS 7. I have a file setup on the public_html like this: -

cms

craft
public

app (this is running a Symfony Framework Web App and runs from app.example.com perfectly)

Now I have the site working from www.example.com but when I login to the back office all of the links say... https://www.example.com/cms/public/admin/dashboard. I want to remove cms/public from the URL links in the back office.

Ok I actually managed to fix this. I moved the index.php file from the cms/public subfolder to public_html and it worked a treat. I had to change the following code:

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

to

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


Forgot Password - Success Message/Flash Message after setting new password on the login screen Quick question about password reset (forgot a password on the front-end)
So I have set my
'setPasswordSuccessPath'           => 'login'
so that when the new password is set, they will be taken to this login screen.
Is there anyway i can detect this has come from this process, so I can show a little flash message to confirm their password has been reset? I'd like to give some visual feedback, without a whole separate interim page.

The way I handle this is by simply includeing the same template as the login page and passing a Twig variable along with it.
So more specifically, my setPasswordSuccessPath is set to a unique template called password-was-reset, which has the following code in it and nothing else:
{% include 'login' with { passwordWasReset: true } %}
You can then read that variable in your login template like this - as you can see I'm also doing the same thing with my account activation template:
    {% if passwordWasReset is defined and passwordWasReset and errorMessage is not defined %}

Your password was reset successfully. Please login below.

    {% endif %}

    {% if accountWasActivated is defined and accountWasActivated and errorMessage is not defined %}

Your account was activated successfully. Please login below.

    {% endif %}

    ...

    <login form here>


Get the category into the url of the product page I'm in the middle of learning Craft Commerce.  When I go to an individual product my URL says /shop/wella-shampoo/.  I'd like it to say /shop/**hair-care**/wella-shampoo/ because this is the category this product falls into.
I've tried adding shop/{categories.first().slug}/{slug} to the URL Format but I get the following error:

Internal Server Error
Craft\Commerce_ProductModel and its behaviors do not have a method or closure named "categories".

It's a bit confusing, but since this product type has variants, using this should work:

shop/{object.categories.first().slug}/{object.slug}

If it didn't have variants, you wouldn't need the object reference in front of it.  The same thing applies if you're referencing a field inside of Matrix as well.

This has been made easier in the upcoming Commerce 2 so you don't have to worry about the differences.


Wordpress-like Subscription Wordpress has a great feature which allows visitors to sign up to receive email notifications whenever there's an update to the site. I'd like to emulate this functionality.

I'm aware of Postmaster, Brief, Sprout Forms, Sprout Emails, MailChimp Subscribe and have read through similar discussions and solutions here on the Craft SE - but nothing that would get me all the way there.

Requirements would be:

Ability to sign up per channel via email (a form per channel)
Confirm email address (double opt-in)
No (Craft member) registration necessary
Ability to unsubscribe
Auto send email notification when new entry is posted

Is there a current solution that could tick all these boxes? If not, would this a possible to build as a plugin?

I would consider this carefully from a subscriber's perspective. i.e. If I received an email every time something was published, I may consider unsubscribing very quickly.
An alternative which I've found works very well is to send email updates on a regular basis - that way your subscribers have an expectation of the frequency.
We've used Campaign Monitor to automatically pull content from a RSS template and then send an email newsletter as well. You also have the flexibility to curate the entries as you see fit.
Have a look at this page/video: https://www.campaignmonitor.com/blog/new-features/2012/03/one-click-content/

Ability to sign up per channel via email (a form per channel)

You can create separate (subscriber) lists within Campaign Monitor, for each Channel/Section

Confirm email address (double opt-in)
No (site) registration necessary
Ability to unsubscribe

These are all possible.

Auto send email notification when new entry is posted

Automation is also possible.
Hopefully that makes sense - let us know your thoughts?


Display User Name in Users Field in CP Is there a way to do this? Emails are pretty ugly when selecting people.

I'm guessing it would be a quick plugin to write, if I wrote plugins. Anyone done this before?

The Users field uses the username for the display label by default when showing what users have been selected.

My guess is you've got the useEmailAsUsername config setting set to true?


Setting relative path to ElementAPI in PHP I need a few small bits of data from Craft in a PHP file. It’s a really small task, so I don’t want to delve into writing plugins or anything hardcore.
It seemed to me the simplest way to approach it would be to use the ElementAPI plugin and then read the resulting JSON in the PHP (this is being tested using MAMP):
<?php

// ID of entry I want
$id = 563;

// Grab data from ElementAPI
$url = "http://localhost:8888/myApi/" . $id . ".json";
$data = file_get_contents($url);
$json = json_decode($data);

// output data
echo "Entry title: " . $json -> title;

?>

This works perfectly.
However, that hard-coded URL does not sit well with me.
I tried grabbing the directory using a few variations, eg:
$url =  __DIR__ . "/myApi/" . $id . ".json";

That gave me the correct path to the file, but the JSON isn’t generated — presumably because without the hard-coded address it’s not running the file through MAMP, so the PHP isn’t running.
I surely cannot manually update the URL every time I deploy a revision — that seems like a disaster in the making.
TIA for any solutions.

You need the url, not the file path. Can you store the url, or the http://localhost:8888 part of it in an environment variable? That gives you
$url = getenv('CRAFT_URL') . $id . ".json";

If it is not already in an environment variable, then in a .env file? web/index.php that comes with Craft is a good example of loading a .env file, and then using the environment variable.


Pagination with users How do I get pagination set up with the following? It should be easy but I'm getting in a muddle.

{% set myUserQuery = craft.users().group('members').order('companyName asc').limit(10).find %}
{% set users = myUserQuery %}

<div class="col-24 gutter-bottom--none flex-container">

  {% for user in users %}
      {% include "includes/_directory-list" %}
  {% endfor %}

</div>

{% include "includes/_pagination" %}

I thought I might be able to do this, but no

{% paginate users %}

{% paginate myUserQuery as users  %}

{% for user in users %}

{% endfor %}

This should help you also.


Webhook plugin & hooking into Contact Form As my first delve into webhooks I've just installed the Pixel&Tonic Webhooks plugin. I'm trying to send data from a front end contact form to Zapier. The front end form uses the Pixel&Tonic Contact Form plugin and the webhook setting is set to the beforeSend event.

I've got the connections working although the webhook doesn't seem to fire automatically. It only sends data to Zapier when I refresh the admin control panel (a 'Sending webhook ...' task displays briefly at the bottom of the control panel's left sidebar).

The email is sending just fine and is immediately received, it's just the webhook that seems to be getting 'stuck'. Is there anything I'm doing wrong?

I had a similar issue where some queues would only run when I logged in via the control panel. The root cause is usually stalled or failed tasks, but I was able to get webhook tasks to run instantly by installing the AsyncQueue plugin.

From their docs:

  This plugin replaces Craft's default queue handler and moves queue execution to a non-blocking background process. The command craft queue/run gets executed right after you push a Job to the queue.


ContactForm error on send I am having problems with the ContactForm plugin. It stopped sending mails.
I'm getting following error after submitting "Could not instantiate mail function."

PHPMail should be working.
I checked with a simple php outside of craft. Also the sendmail option in ContactForm does not work.

I don't now when it stopped working. I thought when I added a second locale, so I added a new test single including a from with only one locale. But that single cannot send the form, too.

Craft Pro 2.3.2626
ContactFrom 1.4

It definitely sounds like whatever mail method you're using isn't configured properly (phpmail or sendmail).  Try swapping to a proper SMTP server and see if that helps or a transactional email provider like Mandrill (https://mandrill.com/) and see if that helps.


How can additional custom fields be added to the Sites settings? In Craft 3 Sites, there are some default fields like language, handle, etc.

I would like to add additional fields. Is this possible. Specifically, I want to add an Image field so we can add a flag that we will use in the front end switcher. We also use Geo location and the Geo location databases have their own country identifiers (e.g. Maxmind returns GB for UK), and so I would like to have a field for the Maxmind country code when creating a site so we can match it.

Is this possible? I could probably create a new channel or globals in which we can enter the Site handle, then fetch this data for the site on the front end, but it would be cleaner to have additional fields in the Sites settings.

Thanks

I would say the easiest thing is to create a set of Globals with all site specific settings. You can include custom settings for sites via Behaviors and Events and include your custom HTML and run custom logic to store those values in custom tables but I doubt it's worth it. A global set should be fine.

By the way: GlobalSets are site specific - you don't need to include a site handle or something. Just insert different settings for each site, Craft will fetch the correct one by itself.

If you want to loop a set for all sites

{% for site in craft.app.getSites().getAllSites() %}
    {% set globalSet = craft.app.globals.getSetByHandle('myset', site.id) %}
    {{ globalSet.myValue }}
{% endfor %}


Member activation query I have a site where am registering users via the front-end.
I want to use email address as username and also want people to define their password on registration.

I have set the following in general.php:

'useEmailAsUsername' => true,
'autoLoginAfterAccountActivation' => true,
'activateAccountSuccessPath' => 'register/success',
'verificationCodeDuration' => 'P1W'

However, when a user registers via the front-end - or I resend the activation link via the Control Panel - they are directed to a page/URL eg actions/users/verifyemail?code=XXXX&id=XXXX and get the following error message:

Oops!

Invalid verification code. Please login or reset your password.

Can't figure out why the verification code is not working.
Any suggestions?

Cole

Solved - bizarre one this.
Was using a third-party email service via SMTP and it was manipulating the URL somehow. Switching to use a direct SMTP connection with a specific email account has resolved.

Go figure!


Show only children relative to current page I have this structure section:

1.0 Nav point level 1
  1.1 Nav point level 2
  1.2 Nav point level 2
  1.3 Nav point level 2
2.0 Nav Point level 1
3.0 Nav Point level 1

I want to show only top level points as long as there is no children ont the current page.

Example:

When im on page 1.0 Nav point level 1 the navi shoud look like above (Because the current page has descendants).

But when im on 2.0 Nav Point level 1 the navi should look like this:
(Everything below level 1 not visible because the current page has no children.)

1.0 Nav point level 1
2.0 Nav Point level 1
3.0 Nav Point level 1

I tried to wrap the children tag into a conditional. But that's not allowed:

{% set topLevel = (entry.level == 1) ? entry : entry.getAncestors().level(1).first()  %}

{% if topLevel.hasDescendants %}

      {% set subnav =  topLevel.getDescendants()  %}

      {% nav page in subnav  %}

            {{ page.title }}
            {% if entry.hasDescendantes %} // this does not work at all.
              {% ifchildren %}

{% children %}

              {% endifchildren %}
            {% endif %}

      {% endnav %}

{% endif %}

I can't wrap my head around it.

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

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

{% for page in pages %}

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

            {% for child in children %}

{{ child.title }}

            {% endfor %}

        {% endif %}

{% endfor %}


Is there a way I can programmatically download the latest version of Craft? If you have a base install script that you use to quickly turn out a new base install for Craft, it would be very useful for that script to be able to download the latest version of Craft when doing it’s new site setup logic.

What’s the best way to do that?

In Craft 3:

You can download the latest Craft 3 release in zip or .tar.gz format by going to:

https://craftcms.com/latest.zip
https://craftcms.com/latest.tar.gz

Or since Craft 3 is Composer based, you can modify your composer.json's craftcms/cms line to install the specific version you're looking for.

In Craft 2:

You can get the latest Craft 2 version in either zip or tar.gz format by going to:

https://craftcms.com/latest-v2.zip
https://craftcms.com/latest-v2.tar.gz


Twig 'starts with' not evaluating variables properly This evaluates to false

{% if block.imageWidth starts with block.imageWidth %}

But this evaluates to true

{% if '{{ block.imageWidth }}' starts with '{{ block.imageWidth }}' %}

Some sort of issue with Craft's Twig integration?

I'm going to assume that your imageWidth field is a dropdown menu... correct me if I'm wrong. When you output a dropdown fieldtype in your templates, it's an object, not a string.

Scenario 1: Comparing objects
{% if block.imageWidth starts with block.imageWidth %}

The starts with comparison operator is designed for strings, but here it's handling two objects. Makes sense that it would just give up and evaluate to false.
Scenario 2: Comparing strings
{% if '{{ block.imageWidth }}' starts with '{{ block.imageWidth }}' %}

In Twig, you can't nest tags. Those strings are being read literally, and not parsed out into their respective values. So what you've got here is a comparison of two identical strings... Makes sense that this would evaluate to true.
Scenario 3: Comparing values
{% if block.imageWidth.value starts with block.imageWidth.value %}

Working under the assumption that imageWidth is a dropdown menu, then you are actually getting an object from block.imageWidth. Twig isn't confident that you actually want a string here, so you'll need to append .value to specifically get the value of your field.

I've seen this trip up a few people, but it makes perfect sense once you wrap your head around it. Many objects in Craft will try to automatically "stringify" themselves when output directly using curly braces. But when it's not a direct output tag, you'll generally need to tell Twig that you specifically want the string value, and not the object itself.


How do I italicize words in an entry title? I'm working on a site with a "Research" channel that is going to have scientific names in the titles of the entries.

What's the best way to allow these names to be marked up with <em> tags so I can display them in italics?

Right now I'm using the default "Title" field Craft supplies when you set up a section, but I haven't needed to insert formatting here before.

I would have the user enter the title with markdown formatting: So they would enter
"Title with *italics*" in the title field, and in the template you would display it with: {{entry.title|md}}


How should an index page be setup/defined in Craft? Site construct question...

I have categories.   Craft knows where to find the template for a category - i.e. markets/{slug}.

But I also have a Markets (categories) page with the first 6 entries for each category (market).  The template is markets/index.html.

The same holds true for and index page with all my entries.  Craft knows where to find an entry posts/_entry - but what about the posts/index page?

How should these pages be setup/defined in Craft - should they be a single page or something else?

Background - Right now, they aren't defined in Craft - but I realize that I probably need to add them to work with an SEO plugin.

Depending on the rest of your site structure, yes you can set these up as Singles.

Your other option is to use an Entry Type inside a 'pages' Structure, and in that template you list the first 6 categories in a defined Category Group (possibly selected in a dropdown, or through craft.request.segment() )

Documentation link on how Craft looks for index templates in case it's useful: https://docs.craftcms.com/v3/templates.html#index-templates.


How to return custom fields in GraphQL This is definitely a noob question, but I can't seem to find an answer to this. (Completely new to GraphQL).

I'm trying to simply return entries:

query test {
  entries(section: "vacancies", limit: 20) {
    title
    expiryDate
    description
  }
}

Since the description is a custom field, this gives an error. How do I get a custom field value?

For anything else than base element fields, you'll need to use an inline fragment to fetch your custom fields like so:

query test {
  entries(section: "vacancies", limit: 20) {
    title
    expiryDate
    ...on sectionHandle_entryTypeHandle_Entry {
      description
    }
  }
}

Replace sectionHandle and entryTypeHandle with your values, I guess something like vacancies_vacancies_Entry


Adding to default classes in a macro I'm fairly new to using macros and haven't found anything online regarding this — sorry if this is a possible duplicate post.

I've created a macro with 7 possible parameters but on different templates I want to add to the default classes.

{% macro button(label, link, width , classes, colours, textclasses, alignment) %}

{{ label }}

{% endmacro %}

Is there a way of doing this without having to set a variable with all the defaults in it and tacking on new classes? For example:

{% set buttonClasses = "absolute w5-ns l-50 tc pa2 pa3-ns ph3 br2 z-max link white f6 flex mt--18 mt--25-ns underline-hover tracked-more" %}
  {% if buttonPosition == 'above' %}
    {% set buttonClasses = buttonClasses ~ " top-0" %}
  {% endif %}
{{ macros.button(block.ctaText, block.ctaLink.one().url, "", buttonClasses) }}

Any help would be appreciated!

— Thanks

Tons of ways to skin this cat; a simple option is to use string concatenation, which could look like the below example. Note that I'm actually creating a new variable for classes at the top of the macro, which IMO helps clean up the markup a little bit and also makes it a bit more clear what's going on – you can continue to do this logic "inline" if you want to, of course.

Also note that the default filter has been omitted from the Twig statement rendering the classes variable; it's redundant now because the classes variable will always be set.

{% macro button(label, link, width, classes, colours, textclasses, alignment) %}
    {% set classes = 'flex pa2 pa3-ns ph3 tc lh-solid f7 f6-ns link underline-hover z-999 br2 mv3 tracked-moreflex pa2 pa3-ns ph3 tc lh-solid f7 f6-ns link underline-hover z-999 br2 mv3 tracked-more' ~ (classes ? ' ' ~ classes) %}

{{ label }}

{% endmacro %}

The important bit is the ... ~ (classes ? classes) part, which basically appends the classes macro parameter to the default classnames, if the parameter is set.

A variation on the above solution, and – in my opinion – maybe a bit cleaner, is to use an array that is joined (i.e. flattened to a string):

{% macro button(label, link, width, classes, colours, textclasses, alignment) %}{% macro button(label, link, width, classes, colours, textclasses, alignment) %}
    {% set classes = ['flex pa2 pa3-ns ph3 tc lh-solid f7 f6-ns link underline-hover z-999 br2 mv3 tracked-moreflex pa2 pa3-ns ph3 tc lh-solid f7 f6-ns link underline-hover z-999 br2 mv3 tracked-more', classes]|filter|join(' ') %}
    ...
{% endmacro %}

Basically, in the above the classes variable is an array containing the default classes and whatever was passed in the classes parameter. The array is piped through the filter Twig filter, which removes any null/undefined values (i.e. it removes the classes parameter value if one wasn't set), and finally join(' ') which merges the two array values together with a space (which means it's now a string and you can do {{ classes }} to print the whole thing).


Loading related entries by category using a select menu I have a list of people (entries) who are related to Categories.

I would like to create select menu which will change (filter) the people (entries) shown on the page depending on which category (option) is selected from the select menu.  I would like the default option to show everyone.

I don't mind if this is done on page reload or via ajax but I really don't know where to start with this one :/

Thanks again

Martin

You can do this using the relatedTo param.

{# Get the selected category ID from a 'catId' query string param #}
{% set catId = craft.request.getQuery('catId') %}

{# Define the 'relatedTo' param value, depending on if there is a category #}
{% if catId %}
    {% set relatedToParam = {
        targetElement: catId,
        field: 'categoriesFieldHandle'
    } %}
{% else %}
    {% set relatedToParam = null %}
{% endif %}

{# Define the ElementCriteriaModel for people #}
{% set people = craft.entries({
    section: 'people',
    relatedTo: relatedToParam,
    limit: null,
    order: 'title asc'
}) %}

{# Output the people #}
{% for person in people %}

{{ person.title }}

{% endfor %}

With this code in place, you just need to update your view so that when a category is selected, this template is re-loaded with a ?catId=X query string, where X is the selected category ID.

The simplest example of that would be with a list of category links:

{% for cat in craft.categories.group('myGroupHandle') %}
    {% set url = url(craft.request.path, { catId: cat.id }) %}

{{ cat.title }}

{% endfor %}


Can Craft be used with conjunction with other framework (Laravel)? Can Craft be used with conjunction with other framework (Laravel) or its a standalone solution?

Craft is frequently used in conjunction with other applications/frameworks. How one would use Craft in coordination with a Laravel application, and whether that would be a good idea, depends on the specific use case.

Most frequently, Craft is used to serve a content API that other applications can consume. Additionally, it's common to se Laravel apps used as an intermediary to broker integrations between the CMS and external services.

In any case, there's no specific technical limitation that would prevent Craft and Laravel from being used in conjunction with each other.


Is it possible to access Twig variables in a plugin variable using PHP? I have a controller that returns route variables to the page:

craft()->urlManager->setRouteVariables(array(
  'errors' => $entry->getErrors()
));

On the page that gets loaded, I can access the variables I set in the template:

{% for error in errors %} ...

However, I want to handle this variable dynamically. Is it possible to access the 'errors' variable in my MyPluginVariable.php file without passing it directly to my variable function?

I don't want to do this:

{{ craft.myPlugin.doSomething(errors) }}

That passes my variable to the plugin variable and I can access it just fine.  But I don't want to ask the user to pass this variable to the function every time, I'd prefer to just handle it in the background.

So, on the page that gets loaded, instead of outputting the variable, can I have a Twig tag like this:

{{ craft.myPlugin.doSomething() }}

And directly access the 'errors' variable in my plugin?  Something like (this doesn't work):

craft()->request->getRouteVariables('errors')

You can’t access the current Twig variables (the “context”, as Twig calls them), from a Template Variable class, but you can access them with a template hook.

From your plugin’s init() function:

craft()->templates->hook('errorCheck', function(&$context)
{
    if (isset($context['errors']))
    {
        // do something with $context['errors'];
    }
});

From your template:

{% hook "errorCheck" %}

You can modify, delete, and create variables within that $context array if you want. And because it is passed by reference (that’s what the “&” does in “&$context”, you won’t need to actually return the array at the end of the function or anything; just make your changes to it.


Show multiple products (urls/pages) on the front-end with dynamic titles/descriptions/meta based on a single product in Craft Commerce I am considered the best way to set this up in Craft and how to handle this with front-end Urls, templates and routes?

So I products with variants for Wheel Spacers, (Wheel Spacers are a product type), these wheel spacers will be related to specific vehicles (vehicles is a separate channel). As these spacers will be related to several vehicles, it doesn't make sense to duplicate them as multiple products.

However, the part I am stuck with is how to list these products in multiple instances on the front-end so that it uses the same product but various information is pulled in from the vehicle. As an example.

Say the product 4x100 56.1 Wheel Spacers (4100561) relates to the following vehicles:

Audi Q7 (2009-15)
Mini Cooper S (2002-2006)
Mini Cooper S (2006-2012)
Mini Cooper (2008-2012)
Mini Cooper (2012-)
BMW Z1 (2012-)

I would like to show the product  4x100 56.1 Wheel Spacers (4100561) as separate pages for each of those models. With each one showing dynamic information for the SEO meta,  and description, this would be pulled in dynamically e.g

Audi Q7 (2009-15) 4x100 56.1 Wheel Spacer
Mini Cooper S (2002-2006) 4x100 56.1 Wheel Spacer
Mini Cooper S (2006-2012) 4x100 56.1 Wheel Spacer
Mini Cooper (2008-2012) 4x100 56.1 Wheel Spacer
Mini Cooper (2012-) 4x100 56.1 Wheel Spacer
BMW Z1 (2012-) 4x100 56.1 Wheel Spacer

At the same time user will be able to browser by product types (Wheel Spacers, Adapters, Fixings etc) but also by Vehicle Manufacture (Audi) and Model (Q7 (2009-15)) etc

If anyone can give me thoughts on the best way to structure this in Craft CMS and how to best structure the templates, the URLs and routes?

Thanks,

Go to admin panel settings->routes
And do something like:

First * is your product-slug, Second * is your variant unique value, could be SKU or some other custom field you have.

Then in your your-product-detail.twig

   {% set productSlug = craft.app.request.segments()[1] %}
   {% set variantUniqueValue = craft.app.request.segments()[2] %}

Then based on these two values, do craft variant query to get variant information and display it.


What's the difference between total function and count function? I found out that the functions count and total on the elementCriteriaModel show different results:

The following examples gave different results. paginate.total was the same as total, but not correct. Only count showed me the correct answer.

{% paginate craft.entries(filterParams).section('object').order('title asc').limit(resultsLimit) as results %}

Total results:{{ paginate.total }}

{% set total =  craft.entries(filterParams).section('object').order('title asc').total() %}
{% set count =  craft.entries(filterParams).section('object').order('title asc').count() %}

.count will return the total results for a particular paginated page (in your case, it should be the same as the resultsLimit variable).

.total will return the number of results in the entire results object regardless of pagination.


Can’t run Craft CMS on my local machine, keep getting message "The Mcrypt extension is required" I try to run Craft on my local Windows server and I keep getting message:

  Can’t run Craft CMS :(
  Your server doesn’t meet the following requirements to run Craft CMS:
  The Mcrypt extension is required.
  Please talk to your host/IT department about upgrading your server.

I tried installing Mcrypt, but I am having no luck... Any suggestions?

Update:

As of Craft 2.7.0, Craft 2 can run on PHP 7.2.

You're probably trying to install Craft 2 using PHP 7.2 (which doesn't have mycrypt installed by default), which isn't supported (see here: https://docs.craftcms.com/v2/requirements.html).

Your options are to:

Use Craft 3, which supports PHP 7.2 and doesn't use mcrypt.
Install mcrypt on PHP 7.2, but you'll probably run into other issues as well.
Stay on Craft 2 and drop down to PHP 7.1.


Internal Server Error I am trying to edit fields.  When I go to Settings->Fields and then click on a field, I get a message that reads:

Internal Server Error

Craft\Model and its behaviors do not have a method or closure named "availableAssetSources".

Then I looked in the utility logs under server info, it reads:

Level:  error
Category:   exception.Twig_Error_Runtime
Message:    exception 'CException' with message 'Craft\Model and its behaviors do not have a method or closure named "availableAssetSources".' in /home/christen/6989-CLG-Web/craft/app/framework/base/CComponent.php:266

I am including the code written on line 266, in case it helps:

throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',

What does all of this mean and how can I fix it?

Thank you so much!

You're running Craft 2.6+ and you've got an older version of the Redactor I plugin installed that isn't Craft 2.6 compatible.  If you download the latest version of the plugin and install it, the error will go away and Redactor I will work as usual.


Creating entries from JSON feed - plugin? I'm wondering if this plugin already exists and I'm just not finding it on Github or via Google. Essentially looking for a CraftCMS version of the ExpressionEngine plugin called "Data Grab" - http://brandnewbox.co.uk/products/details/datagrab

This plugin basically lets you define a feed and run automated imports to create entries. Hoping someone has done this in Craft or has some pointers to a preexisting plugin!

Thanks!

Check out the FeedMe plugin. It's pretty similar to DataGrab and Importer.

From the README:

  Feed Me

  Feed Me is a Craft plugin to make it easy to import entries and entry data from XML, RSS, ATOM or JSON feeds. Feeds can be setup as a task in Craft's Control Panel, or called on-demand for use in your twig templates.

  A common use-case for this plugin is to consume external feeds (news, events), but can also be used as a once-off task for importing content when migrating from other sites.

  Features

  Import data from XML, RSS, ATOM or JSON feeds.
  Feeds are saved to allow easy re-processing on-demand, or to be used in a Cron job.
  Map feed data to your entry fields. See Supported Fieldtypes.
  Duplication handling - control what happens when feeds are processed again.
  Uses Craft's Task service to process feeds in the background.
  Database backups before each feed processing.
  Troubleshoot feed processing issues with logs.
  Grab feed data directly from your twig templates.
  Craft 2.5 compatible.

Disclosure: I authored this free plugin. Let me know if I can be of assistance!


Save same Entry more than once with help of custom relations field Is it possible to save the same Entry (red arrow) twice/more than once in one custom relations field?

"Test Playlist" is a entry in a channel.

Background:

I have set up a playlist, where an entry should be saved more than once.

No, but you could use a Matrix field containing a Entries field.


minify javascript with includeJS If i include javascript in a template using:

{% set myJS %}
//some JS in here
{% endset %}

{% includeJS myJS %}

Is there a way to minify the javascript that gets output on the page? I had a look at the documentation but couldn't find anything. The only way i have found to do it otherwise is to put the javascript in an external file, minify that, and include it with {% includeJsFile %}. Any ideas on how i could do this? Or is there a better way to achieve the same result?

I don't believe there is a way to minify javascript when it is output to the page.  If there is it would make for increased load time. My suggestion is to use a preprocessor like Gulpjs or Gruntjs.

The basic workflow is when you update your JS file/s the preprocessor can detect the change and concatenate and minify your files into a production file.

You will need to install Node.  An easy way to do that is to use Homebrew.

brew install node

I am including links to a couple files to help you start. One is the package.json file that NPM uses to install the node components.  The other gulpfile.js is a starter file for using Gulpjs, to give you an idea of how to setup the tasks.


Spitting out the URL of the entry Bear with me.

Shortly changing a site to run over https vs http - the issue is though that we need to maintain the Facebook open graph share data.

Facebook makes distinction between https and http. The way to maintain this is just to add <meta property="og:url" content="//www.myurl.com/segment/segment" />

Is there a variable I can access that would output the current URL without the protocol?

You could build it up using a couple of the request variables:

{{ craft.request.serverName ~'/'~ craft.request.getSegments | join('/') }}


Inserting data into a table fieldtype via plugin? I'm trying to import data from another database into a 'table' fieldtype via a plugin, and have a couple questions.

When setting the content on the EntryModel, are there any methods to assist in setting the rows and/or columns, or do I need to just format the data as a string in the expected format?

    $entry->getContent()->setAttributes(array(
        'tableFieldHandle' => '[{"col1":"data","col2":"data"}]'
    ));

Secondly, what's the recommended method to prepare strings for a table field (i.e. so as to escape or encode double and single quotes)?

The thing to keep in mind here is that a table field contains a simple JSON string. So you can (and should) use PHP's native json_encode function to prepare your data...

// Your data will be an array of arrays:
$tableData = array(
    array(
        "col1" => "data",
        "col2" => "data",
    )
);

// Then simply encode it when you set your field value:
$entry->getContent()->setAttributes(array(
    'tableFieldHandle' => json_encode($tableData)
));

This will also solve any string escaping concerns for you!


Error when trying to change the database name I get this error when trying to change a database name on a new dev with no entries:

What can be done?

MySQL doesn't have a native command for "Rename database" (well, they did at one point, but removed it shortly thereafter), so any MySQL client that offers that functionality ends up writing their own implementation for it.

That is usually somethings as simple as:

Export data and schema to a backup.
Create new database with new name.
Import data and schema from backup.
Delete old database.

But it looks like phpMyAdmin is trying to be more clever than that and failing.  I would try Lindsey's suggestion as a workaround.

Update

Looking at the error, it looks like you've got a dash (-) in your database table name prefix.  That's considered a "special" character by MySQL and must be escaped in backticks `table-prefix.table-name`, which phpMyAdmin doesn't appear to be doing, so it's likely there is a phpMyAdmin bug there, too.


Advanced query/filter based on date and values I have a channel of events with a field ‘eventDate’ for the date/time of the event. Within that there are ‘types’ of events ‘eventType’. What would be the most efficient way of outputting the NEXT (future date from now) that is of the ‘eventType’ equal to ‘Green’?

So far i’ve got

{% for event in craft.entries.section('events').order('eventDate asc') %}

Which will output the entries in the correct order based on the eventDate, but can i filter the query even further to include the conditionals to only output if the date is in the future like this conditional:

{% if event.eventDate|date("c") > now|date('c') %}

And also include the conditional to only output if the eventType == ‘green’ like so:

{% if event.eventType == ‘green’ %}

So that i can set the ‘limit’ to whatever i want and ONLY have the entries that meet the conditionals be included before that limit is applied?

I know that i can use the 'Search' like so:

{% for event in craft.entries.section('events').search('eventType:green').order('eventDate asc') %}

But A. Is that the most efficient and B. How do i also include only entries that are in the FUTURE from NOW based on the eventDate field?

You're actually closer than you might think. All you need to do is add your field handles as parameters. I prefer to use the hash style of declaring parameters but either way will work, I just find this easier to read.

{% set params = {
  section : 'events',
  order : 'eventDate asc',
  eventDate : '>=' ~ now,
  eventType : 'green',
  limit : '10'
} %}

{% for event in craft.entries(params) %}
...
{% endfor %}

This method also allows you to easily modify the params hash for whatever reason. For example you might want to set the eventType value to be something else based on the value of a query parameter. To do that you could use the merge tag like so:

{% if craft.request.getParam('eventType') not empty %}

  {% set params = params | merge({
    eventType : craft.request.getParam('eventType')
  }) %}

{% endif %}