Site URL displays "Page Not Found The requested URL was not found on this server." but the backend loads fine I've recently installed Craft on a Digital Ocean Ubuntu 12.04 droplet. After finally getting all the permissions set and everything set up I get "Page Not Found. The Requested URL was not found on this server." when I visit the site URL but the admin area loads just fine.

Anybody have an idea of what could be going on? Or maybe a way to debug it? I've checked the Apache and PHP error logs (I think) but they don't show anything strange.

I've also tried a brand new install but also had no luck. I'm guessing it's Apache related but I'm not an apache expert.

Any help would be appreciated.

Thanks!

Got it working! Not really sure exactly what was causing it, but it seems to have had something to do with my Capistrano setup not craft or Apache.


Set up Craft 3 when the craft folder is above public_html on shared hosting I'm trying to setup Craft 3 on a shared host. It succeeds when I place all files in the public directory and then go to /web.

But if I move the craft files to the folder /private_html/craft and the web files in /public_html it won't work (error 500). Do I need to edit the index.php file after all (not mentioned in the installation docs)?

Tried setting the index.php lines to ../private_html/craft/vendor and ../private_html/craft/.env, but no luck. I get the feeling the index.php needs a pointer where the craft folder resides?

<?php

// Set path constants
define('CRAFT_BASE_PATH', dirname(__DIR__));
define('CRAFT_VENDOR_PATH', CRAFT_BASE_PATH.'../private_html/craft/vendor');

// Load Composer's autoloader
require_once CRAFT_VENDOR_PATH.'../private_html/craft/vendor/autoload.php';

// Load dotenv?
if (file_exists(CRAFT_BASE_PATH.'../private_html/craft/.env')) {
    (new Dotenv\Dotenv(CRAFT_BASE_PATH))->load();
}

// Load and run Craft
define('CRAFT_ENVIRONMENT', getenv('ENVIRONMENT') ?: 'production');
$app = require CRAFT_VENDOR_PATH.'../private_html/craft/vendor/craftcms/cms/bootstrap/web.php';
$app->run();

Finally figured out how to edit this index.php file if you're not able to point your document root to the web folder, or if you are forced to put craft in the folder private_html that shared hosters tend to use (or any other given structure above root)

In the index.php file you only need to edit this line:

define('CRAFT_BASE_PATH', dirname(__DIR__));

If your index.php file resides in public_html, __DIR__ will be something like:

/home/hostname.com

To point the index.php to the hidden craft folder, above root, in my case I had to add the folders after the CRAFT_BASE_PATH:

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


Vimeo video with Embedder plugin I am relatively new to Craft and I came across the lovely plugin Embedder and I have managed to make good use of it.

For some reason, I don't manage to apply the paramters. I have followed the advice on the following post but still, don't manage to apply the vimeo paramters.

My code looks like that:

{% set video = craft.embedder.url(entry.workVideo, {max_width:5000, max_height:8000, vimeo_color:ffffff}) %}

{% if video %}
    <div class="work_video">
        {{ video.embed_code }}
    </div>
{% endif %}

All is fine beside the fact that the vimeo_color parameter doesn't work. I have tried other parameters like vimeo_autoplay:true also with no success.

Author of the plugin here - @Lindsey is correct - wrapping the color in quotes is the correct syntax. If you test it with this video, it works fine:
https://vimeo.com/130900978

One thing to note - with Vimeo, a video owner can overwrite this option - so if they set it to a specific theme color, you can't change it through this embed parameter. For more info on the Vimeo API, you can see this documentation: https://developer.vimeo.com/player/embedding


How does a plugin make use of Assets? Within my plugin, I have a need to open an Assets sheet and pick a file that has been uploaded and make use of it in my plugin. How is this possible? I am looking for something similar to the EE version of Assets that will allow me to programmatically use Assets with JS.

Something like this should get you going in the right direction:

Craft.createElementSelectorModal('Asset', {
    multiSelect: true,
    criteria: { locale: this.elementLocale, kind: 'image' }
});

See Brandon's answer here for more information and documentation:
Is it possible to use the ElementType Modal UI for a custom Field Type Plugin?


Can't Install Plugin Via Composer I set up a basic plugin using https://pluginfactory.io/

The package name is kgrote

The plugin name is siteutilities

Then I put it in a subfolder next to my Craft project folder:

/site
|-- craft
|-- craft-plugins
  |-- kgrote
    |-- siteutilities

Then I added this to craft/composer.json:

"minimum-stability": "dev",
"prefer-stable": true,
"repositories": [
    {
      "type": "path",
      "url": "../craft-plugins/kgrote/siteutilities"
    }
]

Then I ran this command in the Craft project folder:

composer require kgrote/siteutilities

Then I got this error:

  Could not find a matching version of package kgrote/siteutilities.
  Check the package spelling, your version constraint and that the
  package is available in a stability which matches your
  minimum-stability (stable).

Here is the contents of my craft/composer.json file:

{
  "require": {
    "craftcms/cms": "3.0.23.1",
    "vlucas/phpdotenv": "^2.4.0",
    "craftcms/aws-s3": "1.0.8",
    "craftcms/redactor": "2.1.6",
    "ether/seo": "3.4.3"
  },
  "autoload": {
    "psr-4": {
      "modules\\": "modules/"
    }
  },
  "config": {
    "optimize-autoloader": true,
    "platform": {
      "php": "7.0"
    }
  },
  "scripts": {
    "post-root-package-install": [
      "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ]
  },
  "minimum-stability": "dev",
  "prefer-stable": true,
  "repositories": [
    {
      "type": "path",
      "url": "../craft-plugins/kgrote/siteutilities"
    }
  ]
}

And here is the contents of my plugin composer.json file:

{
    "name": "kgrote/site-utilities",
    "description": "Helper functions for this website.",
    "type": "craft-plugin",
    "version": "1.0.0",
    "keywords": [
        "craft",
        "cms",
        "craftcms",
        "craft-plugin",
        "site utilities"
    ],
    "support": {
        "docs": "???",
        "issues": "???"
    },
    "license": "MIT",
    "authors": [
        {
            "name": "Kristen Grote"
        }
    ],
    "require": {
        "craftcms/cms": "^3.0.0-RC1"
    },
    "autoload": {
        "psr-4": {
          "kgrote\\siteutilities\\": "src/"
        }
    },
    "extra": {
        "name": "Site Utilities",
        "handle": "site-utilities",
        "hasCpSettings": false,
        "hasCpSection": false,
        "changelogUrl": "???",
        "class": "kgrote\\siteutilities\\SiteUtilities"
    }
}

Don't really know what I'm doing wrong here. How does composer know what kgrote/siteutilities is if it's not defined in the composer.json file? Shouldn't that be part of the "repositories" config setting?

From looking at your plugin's composer.json file, I think you've got the package name wrong – instead of

composer require kgrote/siteutilities

you'll probably want

composer require kgrote/site-utilities

I.e. the plugin folder's name doesn't matter – it's the name entry in your plugin's composer.json file that determines the package name.


How to add a custom panel to the debug bar? I'm working on porting a Yii2 component to Craft CMS as a plugin.
This Yii2 component provides a debug bar custom panel that I'd like to enable
in Craft CMS too.

In classic Yii2 applications, this is done by adding an entry to the
modules.debug.panels configuration directive:

'bootstrap' => ['debug'],
'modules' => [
    'debug' => [
        'class' => 'yii\\debug\\Module',
        'panels' => [
            'elasticsearch' => [
                'class' => 'my\\namespace\\DebugPanel',
            ],
        ],
    ],
],

Unfortunately, Craft 3 seems to hardcode this configuration in the
craft\web\Application::debugBootstrap() method.

How to add a custom panel to the debugbar in Craft 3?

I'm not sure this is the proper way to do it but I got this working.
I used the Yii\Application::EVENT_BEFORE_REQUEST event in my plugin's
init() method:
<?php

namespace my\namespace;

use craft\base\Plugin;
use craft\web\Application;

class MyPlugin extends Plugin
{
    public function init()
    {
        Event::on(
            Application::class,
            Application::EVENT_BEFORE_REQUEST,
            function() {
                /** @var \yii\debug\Module */
                $debugModule = Craft::$app->getModule('debug');

                $debugModule->panels['mycustompanel'] = new DebugPanel(['module' => $debugModule]);
            }
        );
    }
}

At first, I thought about using the yii\base\Controller::EVENT_BEFORE_ACTION
event, but in order to work, the Yii2 component needed to add some routes  and
the EVENT_BEFORE_ACTION event occurs after routing has been done.
Any other event I could think of occurred too early, before Craft had called
the craft\web\Application::debugBootstrap() method.
So far it works but if anyone has a suggestion on the proper way to do it, I'm all hears.

Edit 10/05/2020: it looks like I was almost there. I was just missing the id property in the Panel's constructor parameter. Without it, clicking your panel name in the collapsed debug bar won't open straight away on your panel's tab.
It's also important to check that the Debug module is loaded before adding your panel to it. Otherwise users having the debug bar disabled would get errors.
I found out by looking at the code in Ben Croker's Element Panel plugin.
Event::on(
    Application::class,
    Application::EVENT_BEFORE_REQUEST,
    function () {
        /** @var \yii\debug\Module */
        $debugModule = Craft::$app->getModule('debug');

        if ($debugModule) {
            $debugModule->panels['mycustompanel'] = new DebugPanel([
                'id'     => 'mycustompanel',
                'module' => $debugModule,
            ]);
        }
    }
);


Is it possible to use percentage values for width and height in image transforms? I'm working on creating an image transform to handle retina images. I upload the 2x assets and need an image transform to create my images at 50% their original size. Since images on the site can be varying widths and heights I am currently forced to create a new image transform for each image ratio. Percentage values would cut this down to a single image transform for everything.

It’s possible to do this from your templates:

{% for image in entry.myAssetsField %}

    {% set half = {
        width: (image.width/2)|round,
        height: (image.height/2)|round
    } %}

    {% set halfUrl = image.getUrl(half) %}

    <img src="{{ halfUrl }}" srcset="{{ image.url }} 2x" width="{{ half.width }}" height="{{ half.height }}">

{% endfor %}


Is it possible to filter entries based on entry table field values? I have an entry called "reviews" and within reviews I have a table field with several values. I would like to use the field values to display entry listings in a particular way.

First: I would like to be able to display entry listings so that if the field value is = x to display a particular set of entries.

Second: I would like to be able to display these values so that they are in an ascending order.

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

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

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

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

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

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

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

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

{% endfor %}

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

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


How to compute UK style VAT in Craft Commerce? I'm encountering a problem with how to show UK style VAT tax on an item. I've created a tax rate called VAT at 20% that is included in the taxable subject.

However when this tax is computed on say £8,000 rather than showing the tax as 20% or 1/5th = £1,600 it shows it as 1/6th = £1,333.33. I can't figure out why the tax isn't applying properly. Settings below:

Try unticking the This tax is already included in the taxable subject checkbox.

I would imagine that with this checked, Commerce assumes that the prices entered for products already have tax applied, so the tax amount is calculated on that basis, hence it being 1/6 of the total rather than 1/5.


Custom order related entries is it possible to replicate the order of related entries in the front end as they appear in the admin entries panel? (see images below)

Right now, in the front end it only sorts the order in which the entries where originally entered (sorted by entry date & time).

If not is there any other possibility to do so?
Thanks

The natural sort order for related entries is the order defined in the control panel (not the post date of the related entries), unless you otherwise specify the sort order. Here is an example taken from one of my projects, where related articles are defined within an entries field-type in an article entry:

{% set relatedArticles = entry.relatedArticles %}

    {% for article in relatedArticles %}

{{ article.title }}

    {% endfor %}

On the backend, craft uses the table craft_relations to create the relationship with the columns sourceId, targetId, and sortOrder. This sortOrder column defines the default sort order when accessing related entries through the related 'entries' field-type.

If on the other hand, you are accessing related entries using the .relatedTo() method of the EntryCriteriaModel then you will need to specify the sort order using .order('sortOrder').

Update

Here is the original code:

{% set relatedRecords = craft.entries.section('contenuDiscographie').relatedTo(entry) %}
{% for record in relatedRecords %}
    {{ record.title }}
    {% for block in record.discoArtistes %}
        {% set relatedPerformers = craft.entries.section('interpretes').relatedTo(block) %}
        {% for performer in relatedPerformers %}
            {{ performer.title }}
        {% endfor %}
    {% endfor %}
{% endfor %}

Try using the actual relationship field:

{% set relatedRecords = entry.myRelatedEntriesFieldHandle %}
{% for record in relatedRecords %}
    {{ record.title }}
    {% for block in record.myMatrixBlockFieldHandle %}
        {% set relatedPerformers = block.myRelatedEntriesFieldHandleInsideMatrixField %}
        {% for performer in relatedPerformers %}
            {{ performer.title }}
        {% endfor %}
    {% endfor %}
{% endfor %}

Edit I edited the code above to be more generic, rather than trying to guess what the field handles are named in your project. You need to change these to your actual field handles. From the picture above I would guess they might be 'entry.relatedRecords', 'record.discoArtistes', and 'block.nom' for example.


Reset the password of an admin account I recently inherited a project in Craft from another developer, but he's moved on and no one knows what his admin password was.

I've tried generating a password on an account with a fresh install and copying that over the hashed password in MySQL without success.  Are there any other options?

Thanks.

If you can access the users table, change the admin email to yours, then just use the forgot password link


Image from Another Entry Is it possible to pull an image from another entry? It seems like it would be simple. I've read a lot of posts and documentation, and feel like I'm close...

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

{% for image in entry.podcastItunesImage %}
    <itunes:image href="{{ siteUrl }}{{ image.getUrl}}" />
{% endfor %}

Basically, I'm trying to put an asset field on the Homepage for a iTunes image.

Yeah, I think you are close, you've just go your variables a bit mixed up. You set entries, but then reference entry and I think getUrl should be called as a function getUrl() as it's not a property (it might work that way, I've never tried tbh)

{% set entry = craft.entries.slug('homepage') %}

{% for image in entry.podcastItunesImage %}
 <itunes:image href="{{ image.first.getUrl() }}" />
{% endfor %}

Edit
Oh I don't think you need {{ siteUrl }} when you call getUrl()


Transform Info from Handle? Can I extract a transform's settings from its handle? I'm trying to avoid upscaling images using the workaround, and I'd like to set my transform handle dynamically within some conditionals. (see this link).

Say I'm looping through a matrix field as in the example below, using a dropdown variable to determine which transform is best. When outputting the image I'd like to replace that '970' with pixel width specific to that the asset transform. I'm sure this is wrong, but I'm imagining something like getTransform(transform).width.

{% if block.formation == 'twins' %}
    {% set transform = 'medium' %}
{% else%}
    {% set transform = 'large' %}
{% endif %}

<figure>
  <img src="{% if image.getWidth() > 970 %}{{ image.getUrl(transform) }}{% else %}{{ image.url }}{% endif %}" alt="{{ image.title }}" />
</figure>

Sortof – you can find out what an image’s width would be with a transform applied to it via AssetFileModel’s - getWidth() and getHeigth()

 970 -%}
        {{ image.getUrl(transform) }}
    {%- else -%}
        {{ image.url }}
    {%- endif %}" alt="{{ image.title }}" />

And for extra cleanliness points, you can update the code to use setTransform() instead of jumbling all that code into your  tag:

{% if image.getWidth(transform) > 970 %}
    {% do image.setTransform(transform) %}
{% endif %}


File robots.txt needed in Craft package? I dont understand why we need the robots.txtfile in the Craft CMS package. I think it is confusing. (I had a problem with Google indexing one of my BETA hidden website because of that.)

Reason : When I initiate my domain name on the hosting it creates automatically a public folder inside the virtual host main folder.

So for example my hosting server make the domain name point to /lamp0/web/vhosts/public/. So I just have to upload craft and public folders below in /lamp0/web/vhosts/.
Then I just have to rename public in htdocs and no need of robots.txt file because craft folder is below domain name root.

# Don't allow web crawlers to index Craft
User-agent: *
Disallow: /craft/

=========================
UPDATE
OK I see now in the Craft install documentation (see below). I missed it sorry.
Perhaps would it be good to insert a README.txt file in the package next to robots.txt file to explain that again :)

The specific directive to disallow the /craft/ directory isn't necessary if your craft folder is below the webroot.

However, it's good practice to have a robots.txt for each site, so I don't recommend deleting it altogether. You can change the directives to fit whatever robots criteria you need for your site. (For example, if you launch a beta site, you'd want to Disallow the whole thing to avoid duplicate content penalties.)


ImageMagick generates dark images Is there a workaround when using Craft with old versions of ImageMagick to prevent transformed images from being darker than the original?

I had a look within the Imagine code base and couldn't see a easy fix.

Unfortunately I'm stuck with ImageMagick 6.7.2-7 on shared hosting with no upgrade path.

Try adding this option to your config file (craft/config/general.php)

'preserveImageColorProfiles' => true


What effect does nesting cache tags have? What effect, if any, does nesting cache tags have? It seems like it would be redundant, but are there any inherent drawbacks?

Recently, I can across an instance where I was using the {% cache %} tag in an include to cache a large matrix field. This was very successful at reducing querries and speeding things up on several pages that used that same include.

But one template that included this file used more entries tags so it seemed to make sense to wrap all of them in a cache tag as well. Here's an example.

_includes/article-body.html

{% cache %}
  {% for block in entry.bigMatrixField %}
    ...
  {% endfor %}
{% endcache %}

blog/_entry.html

{% cache %}
  {% for entry in craft.entries.section('blog') %}
    ...(some expensive queries)...
  {% endfor %}

  {% include "_includes/article-body" %}

  {% for category in craft.categories.group('blogCategories') %}
    ...(some more expensive queries)...
  {% endfor %}
{% endcache %}

Nesting cache tags shouldn't cause any new problems (assuming you've taken into account all the fun problems already caused by cache).

Each cache tag will store it's contents in a database table for easier access. We can illustrate this a bit easier using cache tags with keys.  Take the following example with two cache tags using the keys dog and cat

{% cache using key 'dog' %}
    BUSTER
    {% cache using key 'cat' %}
        KITTEN
    {% endcache %}
{% endcache %}

When the cache tags are run they store the following:

cat stores the value:

KITTEN

dog stores the value:

BUSTER
KITTEN

The spacing in my example above may not be perfectly accurate but the gist of what content is stored should be. In the case that the page is loaded a second time, when the dog cache tag is found, Craft will pull it's content from the database.  The cat cache tag will never get run, but it doesn't matter, because the full contents of the wrapping dog cache tag have already been retrieved.


dynamic urls for channel/structure that's linked to the main structure I'm trying to create dynamic urls for a channel or structure section that depend upon the url structure of a different structure (or the first entry in that structure). For example, if the main structure has "foo.com/news/" I want the 'news' channel entries to have urls of "foo.com/news/{slug}".

I came across this question/answer which seems like a great solution: Dynamically setting a channel's Entry URL Format with Craft tags  However, like mentioned it's not really dynamic as you need to go back and resave if the parent slug changes. I started doing this and it's turning into a disaster.

Has anyone found a way to do this completely dynamically? Would routing be the right way and how would it be done (I have not used routing)? Or backwards relational entries from the channel to main structure (which seems much less intuitive from CP UI perspective)?

...and if you don't have any ideas, HOW do you deal with urls when you have a 'pages' structure and linking from that to a channel? Based on extensive research, this seems to be the best way of blending structures and channels but my site is too large and complex to hard-code the url structures for the outlying channels/structures.

I don't have the rep to comment on the post above, hence the new question. Thanks much in advance!

****See my comment below gioppe's answer. I have decided against using this dynamic url approach, as explained in my comment.

I'm not sure to understand what you're trying to solve but... have you tried using the getElementRoute hook to bypass the default Craft routing and apply any custom processing/routing you need?


How to get my craft projectConfig settings inside JS on the front end So I am trying to work with twig templates and I want to inject my project configuration in my js so I can use it.

I can do this

{% set admin_email = craft.app.projectConfig.get.email.fromEmail %}

And this gives me access to {{ admin_email }} anywhere in the document, just like <?php echo $admin_email ?> would do.

But I want to access these settings inside my JS as well. I have some tokens and other things stored inside there.

I tried doing this:

{% js %}
    let admin_email = {{ admin_email }};
    console.log(admin_email);
    alert(admin_email);
{% endjs %}

But in vain. How do I get the settings inside my JS variables?

{% js %}
    let admin_email = "{{ admin_email }}";
    console.log(admin_email);
    alert(admin_email);
{% endjs %}

Missed the "" around the assignment. :)


Craft3, Plugin Craft Commerce, Tax without percentages Is it possible to set Tax in the Rate field other than percentage?.
In Tax I want to place an example amount: 10.50 without percentages.

It's not currently possible to charge a fixed tax fee natively, it needs to be a percentage. You can however implement your own tax adjuster within a plugin or module, which is what Craft is doing under the hood.
You can specify an amount on the adjuster with a type of tax and it will then show on orders within Craft.


Restrict entries to specific users I would like to restrict entries to specific users on the frontend via a User Field called userSelector. It should be possible to have more than 1 user. I understand groups might work, but I feel like it's easier to just select the user(s) directly on the entry.
I know the code below won't work, but hopefully, it shows my intentions a bit more.
{% set users = entry.userSelector.all() %}
{% if currentUser.email == users.email %}
    Show the page
{% else %}
    Permission Denied
{% endif %}

Very open to other suggestions.

If you are faced with such a task, then I think it's better to use user IDs, getting from the method a ids from the field in which users are stored, and check the received array using the in method. Another option is a plugin https://plugins.craftcms.com/user-group-field.
 {% set usersIds = entry.usersField.ids %}

    {% if currentUser.id in usersIds %}
        Show the page
    {% else %}
        Permission Denied
    {% endif %}


Why are my template filenames showing up in Google Analytics This is very odd to me. I am using this in my templates.

{% extends "_layoutGist.html" %}

My layout is showing up in my Google Analytics. GA is showing showing traffic to

/craft/templates/_layoutGist.html

This seams very peculiar as I would think the file would be fully rendered before Google got ahold of it. Is my tracking code in the wrong place?

From my testing it appears that this is an issue with Google's universal analytics.

Based off of Clive's recommendation, my solution what to change

  ga('send', 'page view');

to

  ga('send', 'pageview', {
   'page': '/{{entry.slug}}',
   'title': '{{entry.title}}'
  });

This seems to be holding up well.


Change User Group Front-End I've got a client project which utilizes the Users section of craft pretty heavily. I am trying to figure out if it is possible in vanilla craft to move a user from one group to another say, from the 'employee' group to the 'manager' group. I have seen some code to do it in a custom controller action in a few other posts on here, but I'd rather avoid creating a custom plugin for this if possible.

So is this possible? Thanks!

You'd need to do this from a plugin that has a controller that calls UserGroupsService->assignUserToGroups().


Camera Orientation and image transforms? I have a CraftCMS site and a client has uploaded some images to their portfolio that were taken with their iPhone. Generally I don't worry about the EXIF data/camera orientation but it looks like the transforms are ignoring it.

Looking in Chrome - you can see the issue on this page: http://seachant.co/work/levis-x-vsco

Wondering if anyone else has dealt with this or if there is a quick fix for this in Craft (without having the client save out their photos again)?

The image processing library we use just recently added the support for us to be able to read image EXIF metadata from images, so it's on our list (among other things) to have transforms be aware of image orientation.


Point directly to a structure or channel with Entries field I´m making a Slideshow section, where you create slides ( image, text.. ) and there is one field to specify where the slide links to. This link could be any section of the website. I use entries field to list all websites section, but I need to be able to point to structure or channel directly ( for example, I have a events channel and should be able to point directly to the events list instead of select one specific event).

Any help will be appreciated.

In addition to Aaron's answer, is there a specific page that is going to list the events on the front end? I'm assuming you're probably outputting the events list (for example) via that channel's index page now?

What's nice about Craft is there's lots of way to skin the cat here. It also does some things that aren't necessarily intuitive, like in this case: there's not really a great way to handle the content of the "index" directly or link to it without a couple workarounds.

Linking to a specific section is a little too far removed for my taste but on certain sites with a ton of different sections, I can see where it might be a necessary evil to keep things sane.

Depending on the complexity of the site, I've found creating a master Pages structure that can also double as the navigation to be an option. Authors can see a bird's eye view of their content in Craft's nice tree view. If the top level section happens to be another Channel or Structure, for example, then you can bring it in via your templates.

Doing it that way also gives the benefit of being able to put in introductory text for that section. For example, a Careers page might want to have details about the company before you bring in the jobs; or your Events page might want to mention something about requiring registration, etc.  That makes your Twig logic a bit more complex or tie up an Entry Type depending on what you're doing but it can be manageable. This question goes into more detail about this.

Some people have also used Singles in this way. I find Singles not that useful but again YYMV.

(It would be great to be able to have a Single's functionality—a one-off field layout—in a Structure without having to resort to having to create another entry type that a user can change—but that would be a feature suggestion.)


How to import existing users into database Ok this is now a general question as I managed to import the user table to the database.

Unfortunately it appears that whilst the users all show in the database they do not show in the CMS. Digging a bit deeper it seems they are related to the elements table as each appear to have an entry with a type User.

So my question now is how can you import your existing user list into a new craft set up without breaking it or anything else. With over 10000 users this is not one to be done manually.

Any help appreciated.

You can use an existing import/export plugin that supports handling users, or you can write your own plugin that calls Craft's UsersService->saveUser(), which takes care of saving the right data into the right tables in the database.


PHP Login & Sessions without Craft Commerce? I'm trying to implement this tutorial in my Craft CMS site, I've created all the files and they currently reside in public_html, but twig and the .htaccess of Craft CMS is interfering with it.

Does anyone know what the directory structure should look like to integrate this with craft cms or whether it's possible by other methods?

Appreciate any help.

If you're trying to create a front-end login form, I'd suggest using this as a starting point: https://docs.craftcms.com/v3/dev/examples/login-form.html


How do I prevent a controller from creating unwanted routes? I have a custom module that is adding sections to the CP, like this:

// Register CP routes
Event::on(
    UrlManager::class,
    UrlManager::EVENT_REGISTER_CP_URL_RULES,
    function(craft\events\RegisterUrlRulesEvent $event) {
        $event->rules['<controller:(subscriptions|purchases)>/<action:>'] = [
            'route' => 'module/<controller>/<action>',
            'defaults' => [
                'action' => 'index',
            ],
        ];
    }
);

// Add CP nav items
Event::on(
    Cp::class,
    Cp::EVENT_REGISTER_CP_NAV_ITEMS,
    function(craft\events\RegisterCpNavItemsEvent $event) {
        $event->navItems[] = [
            'url' => 'subscriptions',
            'label' => 'Subscriptions',
        ];
        $event->navItems[] = [
            'url' => 'purchases',
            'label' => 'Purchases',
        ];
    }
);

I have a SubscriptionsController and a PurchasesController, inside of which there is an actionIndex() method that computes some stuff and renders the appropriate template like this:

return $this->renderTemplate('module/cp/subscriptions/index', [
    'stuff' => $stuff,
]);

All this works fine, but I realized that the above registers some URLs that I do not want:

1) Controllers automatically register URLs in the format admin/actions/<module>/<controller>/<action> AND actions/<module>/<controller/<action>. I'm fine with the first one even though it causes duplicate URLs due to my custom <controller:(subscriptions|purchases)>/<action:> rule, but the second one is problematic because they're not even CP URLs, yet they invoke a controller that is only meant to be used in the CP. It's causing an error when trying to render the template, because the module template root is only registered for the CP with the code below:

// Set the base CP template directory
Event::on(
    View::class,
    View::EVENT_REGISTER_CP_TEMPLATE_ROOTS,
    function (craft\events\RegisterTemplateRootsEvent $event) {
        $event->roots['module'] = $this->getBasePath() . DIRECTORY_SEPARATOR . 'templates';
    }
);

2) Craft automatically creates routes based on my template structure, meaning I can render the module/subscriptions/index.twig template directly from this URL: admin/module/subscriptions. This is also causing an error because the template requires variables that are passed to it in the controller action, but they're not set when rendering the template directly. I usually work around this issue on the front-end by setting the general.php config setting privateTemplateTrigger to an empty string '', but it doesn't seem to have any effect on the CP.

Any help with these two issues would be greatly appreciated. :)

After too much time spent on this, I think I found a solution to both issues.

1) To prevent controller actions meant for the CP from being accessible on the front-end (via actions/<module>/<controller>/<action> URLs), simply add this line of code at the top of the action's method:

$this->requireCpRequest();

The non-CP action URLs will now return a 400 error.

2) Although it doesn't seem possible to change the private template trigger on the CP to prevent any template from being directly accessed with a URL, using an underscore at the beginning of any file or folder in the path works. But even better -- the template root itself can be private:

// Set the base CP template directory
Event::on(
    View::class,
    View::EVENT_REGISTER_CP_TEMPLATE_ROOTS,
    function(craft\events\RegisterTemplateRootsEvent $event) {
        $event->roots['_module'] = $this->getBasePath() . DIRECTORY_SEPARATOR . 'templates';
    }
);

Notice the underscore in front of _module. This ensures that the module's templates will only render programmatically.


Set status 'pending' on Guest Entry form I'm using P&T's Guest Entries plugin along with my front end entry forms. All working fine except I want front end entries submitted with status 'pending'. Thought this would be pretty straightforward but something's not right. Atop my form I have:

<input type="hidden" name="action" value="guestEntries/saveEntry">
<input type="hidden" name="redirect" value="success">
<input type="hidden" name="enabled" value="1">
<input type="hidden" name="status" value="pending">

Anyone got statuses working in entry forms?

The "status" on an entry isn't explicitly set like that. It is determined based on other properties of the entry. You will need to set these other criteria for the entry to appear as "pending".

An entry is 'pending' if it is enabled and has Post and Expiration Dates in the future.

More information on status' and the criteria can be found on the docs.

UPDATE: Depending on your use case, the following answer may be helpful: Editorial workflow / custom status


Dynamically iterate over a matrix block's fields? Is there a way to dynamically iterate over a matrix block's fields such that the template doesn't need to know the field handles? This doesn't work:

{% for block in entry.myMatrixField %}
    {% for field in block %}
        {# do something with field #}
    {% endfor %}
{% endfor %}

This seems like a simple thing to want to do but I haven't figured out a way to do it.

Not sure what you want to do with the fields, but you can access them through fieldLayout.

{% for block in entry.myMatrixField %}

    {% for field in block.getFieldLayout().getFields() %}

        {# get properties #}
        {{ field.getField().name }}
        {{ field.getField().handle }}
        {{ field.getField().id }}

        {# get value #}
        {% set handle = field.getField().handle %}
        {{ block[handle] }}

    {% endfor %}

{% endfor %}

You do kind of need to know what the field types are, in order to know how to display them. {{ block[handle] }} will fail for instance if one of the fields is an 'Entry' field, because you can't convert an ElementCriteriaModel to a string. To check the field type you can use field.getField().type;


Set UserGroups for existing User Using Craft::Pro Edition, I want to add a specific UserGroup to an existing User in my module. I tried it this way, but the group is not saved.

$userGroup = Craft::$app->userGroups->getGroupByHandle('partner');
$user->setGroups([$userGroup]);
$success = Craft::$app->elements->saveElement($user);

After (successful) saveElement(), $user->getGroups() still returns an empty array.

When I add the group in the Admin CP, it works, but it needs a password confirmation.

You can assign a user to certain groups via

Craft::$app->getUsers()->assignUserToGroups($user->id, [1,2,3]);

Would assign them to the groups with the ids 1, 2 and 3


How to tweak login logo position? When I add the company logo it appears aligned to the left with a lot of space on the right side. How can I make it appear to the center?

I know that adding background-position: top center; to the CSS aligns it to the center, but I don't know where I can set this change permanent.

You can use this Control Panel CSS plugin to add whatever CSS you'd like.


retrieve assets from an entries Im looking up the last 2 entries like this

{% set entries = craft.entries.section('report').limit(2) %}

My entry got an assets field called 'portfolio'. I would like to retrieve 8 images in random order. How would I do this?

You could try something like:

{% for entry in entries %}
  {% for image in entry.portfolio.orderBy('RAND()').limit(8)
    <img src="{{ image.getUrl() }}">
  {% endfor %}
{% endfor %}


Querying database for slug match? Does anyone know how to query the database to find entry data based on a slug? The only table field I see that contains slug data is in craft_entryversions.data  in json format. Anyone ever tried querying for matches?

If you're talking about querying using SQL directly, then the craft_elements_i18n table is where all of the slugs are kept.


Array to string conversion Template Error I have 2 bits of code that should be about identical with the exception of one being in a Matrix and one not. The bit that is not looks like this:

    {% for point in entry.keyPoints %}

{{ point.heading }}

                {{ point.text }}

    {% endfor %}

This works exactly as intended. and uses the "ICON" 3rd-party field type which essentially is a dropdown that allows me to pick which icon I want to use.

The code that i'm having trouble with is:

{% for block in entry.articleBody %}
    {% if block.type == "text" %}
         Some stuff here
    {% elseif block.type =="iconSection" %}
        {% if block.getPrev() %}
            {% if block.getPrev().type != "iconSection" %}

            {% endif %}
        {% else %}

        {% endif %}

{{ block.heading }}

                {{ block.text }}

        {% if block.getNext() %}
            {% if block.getNext().type != "iconSection" %}

            {% endif %}
        {% else %}

        {% endif %}
    {% elseif block.type =="video" %}
        some stuff here
    {% endif %}
{% endfor %}

It is saying Template Error (Array to String Conversion) with this bit highlighted:

As you can see the code is almost identical except it is BLOCK instead of POINT, and the block one is in a matrix where as the point item is not. What might be causing this and how might I resolve it?

According to the docs for the Icons plugin, icon is actually an object. Try this instead...

In both scenarios, I'd take another look at your rendered HTML... your first example may actually be rendering the word Array instead of the class name that you are looking for. You can also leave off the leading fa-, since that will be automatically included in the class name.

Where you have called icon in both examples, you're simply referring to the field itself. You actually want to be referring to the values of the field.

To output the HTML you're looking for, either of these two options will work:

{{ block.icon.icon }}

And for your non-matrix example, just replace block with point.


"An unknown error occurred" in assets screen I have a number of assets resources all set to upload to the same amazon s3 bucket. Two of my four assets resources show "An unknown error occurred" twice when I view them in /admin/assets.

The files in the folder do not show up. In the logs the following error appears:

Error: Call to a member function format() on null in /apps/cms/craft/app/helpers/AssetsHelper.php:81

When I click Upload files I can upload files, but they do not show up once the upload has finished (no files are shown). They do get uploaded to s3 though. The message "an unknown error occurred" appears again.

Subfolders in that same folder show up perfectly and have all of their content visible and it is possible to upload new images without a hitch.

How can I get the top level folders to work again? What could cause this?

I got an emailed response from Andris from P&T:

  That indicates that at some point Craft was unable to index a file,
  leaving some corrupt data. If you look at craft_assetfiles table,
  you'll notice that at least one entry has the dateModified column set
  to null. Removing those should fix the issue for you. Probably the
  best way to remove them would be to actually delete the records from
  the craft_elements table, that have the matching IDs. The cascading
  delete should remove all related records.

  Please do make backups before tampering with the database, though!

Deleting the records fixed the issues.


Module Development - Get ID of a field within a Matrix field I have a matrix field that has a Supertable matrix within it.

I need to programatically get the ID of the field that is nested in the Matrix.

I have the code below:

$matrixField = Craft::$app->getFields()->getFieldByHandle('myMatrixFieldHandle');

Which gets me my Matrix field element, but I can't figure out how to get the fields that are within that Matrix field and thus the ID of the field within the Matrix field.

Any help appreciated!

You'll need to loop through the fields in the blocktype definition for your Matrix field. For simplicities sake, I've supplied a loop, which you can cut-down if you have a specific block type in mind you just want to fetch for:

$matrixField = Craft::$app->getFields()->getFieldByHandle('myMatrixFieldHandle');

foreach ($matrixField->getBlockTypes() as $key => $blockType) {
    Craft::dump($blockType->name);

    foreach ($blockType->getFields() as $key => $field) {
        Craft::dump($field->name);
    }
}


Tag overview in the Craft backend Is there a possibility or plugin that I can see all my tags that I am using on my Craft page?

So that I can edit the tags when I, for example, wrote some tags wrong or just want to delete some and so on.

All the best.

There is a Tag Manager plugin you can use for this.

You might also want to consider voting for this feature request if you think this should be in core!


How to get an element query into json (for vue) without extra data? Lets say I want to get a list of category names and ids and pass them into JSON (for vue.js).

This is how I'm currently doing it:

{% set sections = craft.categories.group('teamCategory').select(['title','elements.id','groupId']).all() %}

<!-- My vue.js tag: -->
<team :sections="{{ sections|json_encode() }}"></team>

My problem is that I only want title and id to be passed to vue, but craft/twig is passing load and loads more data that forms part of the category object.

Is there an easy way to just pass the array columns I need?

You can use the asArray function to return arrays instead of elements

{% set sections = craft
    .categories
    .group('teamCategory')
    .select(['title','elements.id','groupId'])
    .asArray()
    .all()
%}


Update Asset Indexes on Login I'm using an assets directory with Amazon S3 and I have to manually update the indexes through the control panel after uploading files externally. Does anyone know if it is possible to do anything custom to do this on login. Or is it possible to set up a URL that could be hit with a cron or manually.

One idea I had failing any of the above would be to do a custom plugin with just a button to make it a bit quicker than the current method through the settings.

Updating Asset indexes is pretty coupled to the tool in the Settings portion of the control panel.

But if you wanted to try and duplicate that functionality in a plugin, you could have it listen for the onLogin event to do your business.


Craft CMS 3 - Entries field, getURL Just migrating a site from 2 to 3 and stuck on this little call, cannot find anything in the docs at all.

Matrix field, Entries.

<a href="{{ entry.featuredProjectLink.getUrl() }}">

Cannot for the life of me find the equivalent/new way in the docs.

TIA

entry.featuredProjectLink is not an element or an array of elements, it is an object of type MatrixQuery in order to fetch elements you have to use the .one() or .all() function

<a href="{{ entry.featuredProjectLink.one().getUrl() }}">

Element Queries

Relations -> the "Going Through Matrix" part is the thing you want


Get category title by slug I'm setting my categories by matching the third segment to a category slug. How do I get the category title?

{% set catSlug = craft.request.getSegment(3) %}
{% set category = craft.categories.slug(catSlug) %}

{{ category.slug }} returns the slug, but {{ category.title }} returns nothing.

You need to add .first() when setting the category. As far as I can tell, if you don't have .first() only {{ category.slug }} will work.

First get the slug:

{% set catSlug = craft.request.getSegment(3) %}

This will give you the CategoryModel object for catSlug:

{% set category = craft.categories.slug(catSlug).first() %}

You can now access whatever you want from the category, like the title:

{{ category.title }}


Combine AND and OR in a ElementQuery I have a category with 2 levels. And I want to be able to let the user do a search based on those. The problem is that it needs to be AND between all level 1 categories, and OR within child categories. So let's say I have a category structure like this:
- Elevator
- Air condition
- View
  - Ocean
  - Mountains
  - Garden

Now when a user selects elevator, ocean and mountains I want to return all entries that have elevator AND (ocean OR mountains)
I tried this: $entries->categories(['and', 695, ['or', 698, 697]]);, but that doesn't work, as it seems to just skip the ['or', 698, 697] part.
Edit for bounty: In addition to the reason given above, there is also a change in the requirement since we added multiple categories. So for one category group, the operator needs to be OR, and some groups should have AND.

If I understand properly, you should be able to do this:
$entries = \craft\elements\Entry::find()
    ->section('yourSection')
    ->category(['and', 695])
    ->relatedTo([698,698])->all();

Assuming category is the name of your relational field, you can use that to pass the and condition (though with one element only it wouldn't be needed) then relatedTo is an or by default (docs)
And as per your edit, pass and condition to your custom fied and or conditions to your relatedTo.
It would be pretty much the same in Twig.


Redactor pagebreak plugin and linking to pages I am trying to split entry into multiple pages.

In accordance with the docs, I am using this code on single-entry template:

{{ entry.body.getPage(1) }}

{% if entry.body.getTotalPages() > 1 %}
  Continue reading…
{% endif %}

However {{ entry.url }} is always pointing to the same page that I'm on (base entry URL) without any pagination number, so I never get to second page.
I have checked that {{entry.body.getTotalPages()}} returns 2, so the pagebreak plugin is working.

What am I missing here?

Answer:

Here's the working code that I got with Brad Bell's help:

{% set currentPage = 1 %}
{% if craft.request.getParam('page') is not empty %}
    {% set currentPage = craft.request.getParam('page') %}
{% endif %}

{{ entry.body.getPage(currentPage) }}

{% if entry.body.getTotalPages() > 1 %}
    {% set totalPages = entry.body.getTotalPages() %}

    {% for i in 1..totalPages %}
    go to page: {{ i }}
    {% endfor %}
{% endif %}

The example is the docs you're referring to will simple output the first "page" of the Rich Text field and if there are more pages show a "Continue Reading" link that loads the full entry.

For the functionality you're looking for you'd have to do something like this (completely untested):

{% set totalPages = entry.body.getTotalPages() %}

{% for i in 1..totalPages %}
    {{ i }}
{% endfor %}

Then your template would grab the page from the querystring and display it  using entry.body.getPage(page).


The Tag ‘name’ property has been deprecated. Use ‘title’ instead I keep seeing this deprecation message every time I upgrade Craft and cannot figure out what's going on for the life of me. There is nothing in the stack trace (that I can see) that points to a specific template file.

Below is the full stack trace:

> Deprecation error: The Tag ‘name’ property has been deprecated. Use ‘title’ instead.

>Called from /Users/Rhys/www/madebydusk.com/live/craft/app/models/TagModel.php (109)

>16 Craft\TagModel::getName() Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/base/CComponent.php (111)

>15 Craft\TagModel::__get("name") Called from /Users/Rhys/www/madebydusk.com/live/craft/app/models/BaseModel.php (87)

>14 Craft\TagModel::__get("name") Called from /Users/Rhys/www/madebydusk.com/live/craft/app/models/BaseElementModel.php (141)

>13 Craft\TagModel::__get("name") Called from /Users/Rhys/www/madebydusk.com/live/craft/app/services/SearchService.php (78)

>12 Craft\SearchService::indexElementAttributes(Craft\TagModel) Called from /Users/Rhys/www/madebydusk.com/live/craft/app/tools/SearchIndexTool.php (99)

>11 Craft\SearchIndexTool::performAction(array("id" => "340", "type" => "Tag")) Called from /Users/Rhys/www/madebydusk.com/live/craft/app/controllers/ToolsController.php (50)

>10 Craft\ToolsController::actionPerformAction() Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/web/actions/CInlineAction.php (49)

>9  CInlineAction::runWithParams(array()) Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/web/CController.php (308)

>8  Craft\ToolsController::runAction(CInlineAction) Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/web/CController.php (286)

>7  Craft\ToolsController::runActionWithFilters(CInlineAction, array()) Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/web/CController.php (265)

>6  Craft\ToolsController::run("performAction") Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/web/CWebApplication.php (282)

>5  Craft\WebApp::runController("tools/performAction") Called from /Users/Rhys/www/madebydusk.com/live/craft/app/etc/web/WebApp.php (817)

>4  Craft\WebApp::_processActionRequest() Called from /Users/Rhys/www/madebydusk.com/live/craft/app/etc/web/WebApp.php (287)

>3  Craft\WebApp::processRequest() Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/base/CApplication.php (185)

>2  Craft\WebApp::run() Called from /Users/Rhys/www/madebydusk.com/live/craft/app/index.php (62)

>1  require_once("/Users/Rhys/www/madebydusk.com/live/craft/app/index.php") Called from /Users/Rhys/www/madebydusk.com/live/public/index.php (19)

As mentioned in the comments by Brad, this is a bug and has been fixed in the next release.


Mailgun (SMTP) + Craft I'm trying to set Mailgun up on Craft (Like we've done plenty of times before) but each time it keeps saying that the connection to SMTP is failing.

The error I'm getting is:

  2017/03/29 09:54:13 [error] [application] Email error: SMTP Error: Could not authenticate.

I've checked https://craftcms.com/support/troubleshooting-email-errors#dealing-with-errors and error description is:

  “Use SMTP authentication” was checked, but the credentials were incorrect.

But I've double checked these details over 10x now and they are 100% correct.

Is there any other reason this could fail? We're using port 587 and tried other ports but no success. Even opening these ports on the server doesn't connect.

Where would the problem be... Craft, Mailgun or Server?

Craft is just passing on the error message it gets back when trying to connect with whatever settings it was given.

And we're using Mailgun ourselves (port 587) for sending emails on https://craftcms.com, which is a Craft install.

Make sure you're using smtp.mailgun.org as the host and that you've got the transport type set to TLS as well.


Setting a new / override shippingAddress via axios I am trying to change/set a customers shippingAddress via axios

It does work e.g. for setting the shippingMethod or the quantity for a product. However if i want to set a new shippingAddress the axios post fails with a 500 status

This is my axios post request:

updateShipping() {
        const options = {
            method: 'POST',
            headers: {
                'content-type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': window.Craft.csrfToken,
            },
            data: qs.stringify({
                shippingMethodHandle: 'standardShipping', //works
                shippingSameAsBilling: false, // wont work
                shippingAddressId: 'new', // wont work, also tried an existing
                shippingAddress: {
                   firstName: 'test',
                   ...
                },
            }),
            url: '/actions/commerce/cart/update-cart',
        };
        axios(options)
            .then(response => {...})
            .catch(error => {...});
    },

Stumbled over the old questions, this is how it works:

updateShipping() {
        const options = {
            method: 'post',
            url: '/actions/commerce/cart/update-cart',
            headers: {
                'X-CSRF-Token': window.Craft.csrfToken,
            },
            data: qs.stringify({
                shippingMethodHandle: 'standardShipping',
                shippingSameAsBilling: 0,
                shippingAddressId: 123, // remove if it doesn't exists or is new
                shippingAddress: {
                   id: '', // only needed if address is new
                   firstName: 'test',
                   ...
                },
            }),
        };
        axios(options)
            .then(response => {...})
            .catch(error => {...});
    },


How to use promotable Boolean in Craft Commerce? I'm sure this is somewhere in Craft documentation but I cannot find anything on it. There is that checkbox in the product area that says "Promotable". I'm assuming this is so I can reference it later in the code (which is why I'm interested in this box), but I've browsed through the documentation and found nothing about it. The lack of questions about it on here makes me assume I just missed it. Could I get an explanation or a link? Thanks!

In Craft Commerce?

  promotable (true or false)
  Is this product and its variants able to be on sale or at a discount.

https://craftcommerce.com/docs/product-model#promotable


Invalidate cache from two channel expiry dates I have two channels: A event and a news channel which I want the cache to expire based on both their expiry Date.

{% set newsDate = craft.entries.section('newsDate').order('expiryDate asc').first() %}
{% set eventDate = craft.entries.section('event').order('konzertStartdate asc').first() %}
{% set currentTime = now |date('c') %}

{% if currentTime <= newsDate %}
    {% set invalidate = newsDate.expiryDate | date('c') %}
{% else %}
    {% set invalidate = auffuehrung.konzertStartdate |date('c') %}
{% endif %}

{% cache unless invalidate %}
 {# blablabla #}
{% endcache %}

As you can see I create two variables and then check which one is newer. But its not working properly.

The news never seem to invalidate the cache.

Do you know a better way to do this?

the error was with the date format in the date comparison conditional and the until tag instead of unless

{% if currentTime <= newsDate | date('c') %} {# those two dates were formated differentely #}
    {% set invalidate = newsDate.expiryDate | date('c') %}
{% else %}
    {% set invalidate = auffuehrung.konzertStartdate |date('c') %}
{% endif %}

{% cache until invalidate %} {# not unless #}
 {# blablabla #}
{% endcache %}


How can I add buttons to the sidebar? I can't find a way to include buttons on the correct place at the sidebar of my plugin.

So I noticed that on the sidebar markup, there's a div for buttons, there's created automatically:

I can easily add anything to the sidebar, I can include the buttons on the top, as you can see on the example, but my question is, how do I add the buttons to that div?

I couldn't find on the templates the correct place.

[EDIT]

Here's my template.

{% extends "_layouts/elementindex" %}
{% includeCssResource "crashC/css/crashC.css" %}

{% set title = "Entries" %}
{% set selectedTab = 'entries' %}
{% set elementType = "CrashC" %}
{% set docsUrl = '' %}

{% block sidebar %}
  Download CSV
  {{ parent() }}
{% endblock %}

Thanks a lot for the help!

I found a solution for this one, actually, you can do this with:

Javascript: Craft.elementIndex.addButton($('').html('test'))

Template: Just add a div with class .buttons, Craft's javascript will check for that and you won't get duplicated divs.

{% block sidebar %}

     Download CSV

  {{ parent() }}
{% endblock %}

Done.
I hope this helps others too.


How do I archive a user from a plugin I want to archive users from a plugin, but can't seem to find the appropriate method to do so (not even in the control panel). I can suspend, delete, but not archive.

Any ideas?

I assume you're referring to the archived column in the craft_users table in the database.

Originally we were going to use that as a way to "soft delete" different elements in Craft (Users, Entries, etc.), but never got around to implementing it for various reasons, so there is no UI for it and no backing code to support it currently.


Outputting supertables within a matrix after searching around for awhile I still cannot find a clear answer to templating Supertables within a matrix field.

I have a field called 'about' which is the matrix field, within that there is a block called 'biography' which holds both a Rich Text Field called 'copy', and a SuperTable field called hgroup, within hgroup there is a plain text field called heading. How do I go about outputting these within the template.

There are other blocks, similar to 'biography', but I'm encountering the same issue with them.

I'm still very new to CraftCMS so some of this has me puzzled.

{% block content %}
  {% for block in entry.about %}
    {% switch entry.about %}
        {% case 'biography' %}

                {% for row in entry.hgroup %}

{{ entry.heading }}

                {% endfor %}
                  {{ entry.copy }}

    {% endswitch %}
  {% endfor %}
{% endblock %}

Thanks.

I think your output is wrong. Looking at your code and explanation, {% for row in entry.hgroup %} should be: {% for row in block.hgroup %}

Same goes for {{ entry.heading }} This should be: {{ row.heading }}

Copy should be: {{ block.copy }}

Working with matrixes and Supertable's is hard in the beginning but you'll get the hang of it.

When you loop over you {{ entry.about }} you loop using a variable named block. that should be used for every field you want to output that's in the matrix field. Same goes for SuperTable's only just one layer deeper.


Search without leaving or refreshing page I'm trying to do a simple search of all posts, and using this: https://craftcms.com/docs/templating/search-form

It works but in that example it assumes you display search results on another page. I am trying to build this as a single-pager (it's a really basic site). I've tried reloading the page (i.e. setting url to the current page) and this works . . . however I also want to show/hide elements on search, and this is getting lost with the page reload.

I have a feeling this is going to be something basic, but am stumped . . . have been playing around with it, trying includes and stuff, and getting nowhere. My apologies if it's a noob question.

Search Results

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

    {% if entries|length %}

{{ entries|length }} results:

          {% for entry in entries %}

{{ entry.title }}

          {% endfor %}

    {% else %}

Your search for "{{ query }}" didn’t return any results.

    {% endif %}

So that is the code. I only want the search results appearing when the user searches (obvs) but want them on the main page (i.e the same page as the search form)

Here is the show/hide code if it helps at all:

var searchForm = document.getElementById("searchForm");
var revealedOnSearch = document.getElementById("revealedOnSearch");

searchForm.addEventListener("submit", function(){
    revealedOnSearch.style = "display:block;";
});

Here is some example code that should probably help you get things set up. The relevant part is the line {% if query|length and query.search %}, where you’d test if there’s a query string at all and additionally if the search param is set (you can leave out that part if you want).

{% set query = craft.request.getQuery() %}

<form action="">
    {% set value = query.search is defined ? query.search : '' %}
    <input type="search" id="search" name="search" value="{{ value }}" autocomplete="off">
    Search

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

{% if query|length and query.search %}
    {% set entries = craft.entries.search(query.search) %}

Search Results

        {% if entries|length %}

                {% for entry in entries %}

{{ entry.title }}

                {% endfor %}

        {% else %}

No results.

        {% endif %}

{% endif %}


How to display picture I started working on Craft today. I want to display a background CSS image by adding a rule.

Should I manually copy the file in assets folder or there's some way to upload and refer it on page.

If you need the background image to be dynamic and controlled by the client then I would recommend using inline CSS in the template to set the image path. The rest of the required CSS can be in the CSS file itself.

e.g.,

<div style="background-image: url('{{ entry.image.first().getUrl('transformName') }}')" class="thing" ... >

Your CSS file could even have a fallback background-url
and in your CSS

.thing { background-size: cover; ... }


Fetch entries with special characters in title When trying to fetch an entry with special characters in the title, it doesn't seem to match.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->title = "Title,with,commas";
$entry = $criteria->first();

I've also tried a few other characters such as #, %, and $ with the same result - $entry is empty.

Have a look at DbHelper::parseParam docs:

  If the $value is a string, it will automatically be converted to an array, split on any commas within the string (via ArrayHelper::stringToArray()). If that is not desired behavior, you can escape the comma with a backslash before it.

To escape the comma and other characters treated as special in DbHelper::parseParam use the DbHelper::escapeParam helper:

$criteria->title = DbHelper::escapeParam("Title, with, commas");


craft.fields.getFieldByHandle() has been deprecated I'm querying a dropdown field to loop through all of the options and followed best practice (so I thought) in the twig template. Does anyone know how to update for the deprecation below?
Deprecation message:

craft.fields.getFieldByHandle() has been deprecated. Use craft.app.fields.getFieldByHandle() instead.

Code line:
{% set siteOptions = craft.fields.getFieldbyHandle('siteSelector').settings.options %}

You should replace craft.fields.getFieldbyHandle() with craft.app.fields.getFieldByHandle() (note the additional .app in there).


Ajax not updating user image I have ajax submitting my form everything works except the user image. It works without ajax but not sure why it's not working with ajax. My ajax is and form are shown below.

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

    {{ csrfInput() }}

    <input type="hidden" name="action" value="users/save-user">
    <input type="hidden" name="redirect" value="account">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">
    {{ redirectInput('my-program/account') }}

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

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

    <input type="hidden" name="userId" value="{{ currentUser.id }}">

            {% if currentUser.getPhoto != '' %}

            {% else %}

            {% endif %}
            <input type="file" id="userPhoto" name="photo" value="Upload">

Change Avatar

                Name

                <input type="text" id="fullName" name="fields[fullName]" value="{{ currentUser.fullName }}">

                Role

                <input type="text" id="userRole" name="" value="Your Role here">

                company

                <input type="text" id="company" name="fields[company]" value="{{ currentUser.company }}">

                email

                <input type="text" id="email" name="fields[email]" value="{{ currentUser.email }}">

            <input type="submit" value="Save Changes" id="saveProfile" class="dark-btn">

</form>

$("#profile-form").submit( function(e) {
    e.preventDefault();
    var data = $(this).serialize();

    $.ajax({
        method: "POST",
        url: "users/save-user",
        data: data,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        success: function(data, response){
        }
    });
});

You can't just upload files via serialized form data by default with jQuery. I suggest you to create a new FormData instead and append the files from your input, so you need to grab them first

You can see a good guide simple file uploads


How to make plugin developer name available in templates? I'm constructing a plug-in and I'm new to it.

I want to print to the screen in my template the name of the developer, by accessing the getDeveloper() method in my Plugin.php. The problem is instead of showing the name of the developer, it throws an error saying Class Craft\CrmPortalVariable not found.

Data in plugins is not automatically made available to twig templates.

To make something available, you need to create a folder in your plugin master folder called variables and in that folder create a class PluginNameVariable.php

Here's an example of what you might put in that file:

<?php

namespace Craft;

class YourPluginNameVariable
{

    public function developerName()
    {
        return craft()->yourPluginsName->someServiceMethodThatReturnsTheDeveloperName();
    }

}

This would make a template variable available in your templates via

{{ craft.yourPluginName.developerName }}

Here are the Craft Docs for this - https://craftcms.com/docs/plugins/variables


Call Module Function from Front End I'm looking to call the following Module function from a front end form. I've looked through numerous answers but I can't seem to find a definitive answer on this.

Here's my Module's code, but obviously I don't want this to run every time and entry get's saved, but when the form on the front-end calls it.

<?php

namespace modules;

use Craft;

use yii\base\Module;
use yii\base\Event;
use craft\services\Elements;

class ShifterModule extends Module
{
    public function init()
    {

        parent::init();

        Event::on(
            Elements::class,
            Elements::EVENT_AFTER_SAVE_ELEMENT,
            function (ElementEvent $event){
                // Get the correct Entry that's currently saving
                if ($event->element instanceof craft\elements\Entry) {
                    $entry = $event->element;
                    // Set $field to the Field Value
                    $field =  $entry->getFieldValue('proposalStatus');
                    // Set the Proposals > Campaign Authors Email
                    $owner =  $entry->getFieldValue('proposalCampaign')->first()->getAuthor()->emailAddress;

                    if($field == 'delivered'){
                      return Craft::$app
                          ->getMailer()
                          ->compose()
                          ->setFrom('test@test.com')
                          ->setTo($owner)
                          ->setSubject('Proposal Delivered!')
                          ->send();
                    }
                }
            } // Close Function
        ); // Close Event
    } // Close Public Function
} // Close Module Off

You could use Craft::$app->getRequest()->getIsCpRequest() (docs) and do something like this in your innit:

public function init()
{
    parent::init();

    if (!Craft::$app->getRequest()->getIsCpRequest()) {
        // Listens for EVENT_AFTER_SAVE_ELEMENT and element instanceof Entry
        self::newEntryElementIsSaved();
    }
}

Then further down add:

protected function newEntryElementIsSaved()
{
    Event::on(
        Elements::class,
        Elements::EVENT_AFTER_SAVE_ELEMENT,
        function (ElementEvent $event){
            // Get the correct Entry that's currently saving
            if ($event->element instanceof craft\elements\Entry) {
                $entry = $event->element;
                // Set $field to the Field Value
                $field =  $entry->getFieldValue('proposalStatus');
                // Set the Proposals > Campaign Authors Email
                $owner =  $entry->getFieldValue('proposalCampaign')->first()->getAuthor()->emailAddress;

                if($field == 'delivered') {
                  return Craft::$app
                      ->getMailer()
                      ->compose()
                      ->setFrom('test@test.com')
                      ->setTo($owner)
                      ->setSubject('Proposal Delivered!')
                      ->send();
                }
            }
        } // Close Function
    ); // Close Event
}


How to create a border + border colour field on an image My first question here... maybe one of a few! I've inherited a Craft project recently and don't have much experience with it.

I want to allow admin to set a border (and border color) whenever they add an image. Currently, the image field has a field type of Assets. I don't want to change the field type (to a Super Table or similar) because the component is used in so many other places - it would break.

We're using Craft 2 but upgrading to 3 presently.

Has anyone else had to do this before? Any suggestions on how to approach this? Let me know if I can clarify anything.

It looks like you're using a Matrix block with a field inside a block called Image. Given that information, I'd add a new field to that block called Border. You could either use a colour field, or a dropdown to set your own values. Then maybe something like this on the front end:

{% if block.image|length %}
<img src="{{ block.image.one.url }}" {% if block.border|length %} class="bordered border-{{ block.border }}"{% endif %}>
{% endif %}

Craft doesn't have any relation to the front end of your site intrinsically, so you could call the field whatever you like.


Table 'craft.craft_elementindexsettings' doesn't exist I have a local site that was running perfectly, but last year when I ran the auto-update it seems that it did not finish the process. At that time didn't have time to have a look to what happened (please bear in mind I'm a designer, and this is not a client site :D), and yesterday I saw that the admin dashboard was not working, and some pages were not loading too.

I downloaded the files again from the website, replaced the craft/app folder following the manual update instructions, and all seem to be fine (site works and dashboard works), except that when I go to entries I get this error:

  CDbCommand failed to execute the SQL statement: SQLSTATE[42S02]: Base table or > view not found: 1146 Table 'craft.craft_elementindexsettings' doesn't exist

Other pages of the admin side works fine, I've cleared the cache and that made no difference.

When I uploaded the new craft/new and went to /admin, I did not get any message about updating the database as the instructions say.

I also can't recall why the auto-update didn't work properly. I kind of remember that the page got stuck, or I got an error, but as the internet in this office is quite bad, I thought the problem was at my end, not craft.

Any ideas on how to solve it?
Is it possible to re-run the auto-update of the database?

This issue has actually come up before in the Slack channel...

  "That’s a brand new Craft 2.5 table, so you’ve probably tried to do the update before, it failed and you didn’t clear out all tables from the database when you retried." - Brad Bell

As you mentioned, your auto-update did not complete successfully. So the logical next step (as you tried) is to perform a manual update.

But here's the catch... Before you made your 2nd (manual) attempt, you didn't roll back your database. Between attempts, you would need to drop all tables and re-import your original database SQL file.


Dynamic asset subfolder path for Craft Commerce I have a asset field where I would like to save the images in dynamic folders.
The upload folder should be parsed for the Dropdown field values in a Matrix field.

For a normal Dropdown field it works with

{{ object.dropdownFieldHandle }}

but for a Dropdown field in a Matrix field i can't get it working.

Any help is very appreciated. Thank you in advance.

If you have an Asset field outside of Matrix and you want to set its "Upload Location" to be a dynamic value of Dropdown field inside of a separate Matrix field, something like this should work:

{{ object.matrixFieldHandle.type('matribBlockHandleTheFieldLivesIn').first().dropdownFieldHandle.value }}


for loop: get the title of the first element of an entries field I want to get the title of the first element from a entries field in a for loop. I think its easier to understand with a code example:

{% set programs = craft.entries.section('program_point').block.first().title('first-block') %}
{% for program in programs %}
...
{% endfor %}

block is an entries field. And the loop should only consider entries where the title of the first element in blockis first-block.

When I tried this, I always got an error:

  Impossible to invoke a method ("title") on a null variable

But when I did this:

{% set programs = craft.entries.section('program_point') %}
{% for program in programs %}
        {% if program.block.first().title == 'first-block' %}
             ...
        {% endif %}
{% endfor %}

all worked fine.
So how can I check the title of the first element in the for loop?

I could be not following correctly, so I apologize if I'm way off here.

If you want to grab all entries that are selected in your block field, but only want to single out the first one, you could do something like this:

Program Points

{% for entry in craft.entries.section('program_point') %}
    {% if loop.first %}

{{ entry.title }}

    {% else %}

{{ entry.title }}

    {% endif %}
{% endfor %}

The twig for loop has some pretty cool stuff built in that you could leverage to check for the first entry.

Hope this helps!


Adding a cite tag within the blockquote tag using redactor's WYSIWYG? I have a rich text field that needs to have the cite tag within. See here:

It is currently ouputting as:

    This is the quote.

Whereas I need to work in an option for the client to create this:

    This is the quote.

        John Doe, Founder

What options are there for formatting some copy to be within the blockquote tag, but then formatting some of it to be wrapped in cite tags?

Thanks,
Jay

You can use the Redactor Inline Styles add-on then use the following in your Redactor json config:

"plugins": ["source","fullscreen","inlinestyles"],
    "buttonsAddAfter": "italic",
    "buttonsAdd": {
        "cite": {
            "title": "Cite",
            "args": ["cite"]
        }
    }

You'll then be able to add a cite element within a blockquote formatted text.


Measuring Template Performance I've got a news website built and I am in the process of improving it's performance. What would be the best way to measure the performance of my templates?

I can use Chrome Developer tools to measure how long it takes for the server to respond but is that the best way of doing it or can I do it internally?

If you enable devMode, you'll get code profiling information (execution times, memory used, stack traces, etc.) that you can use to debug templates with in your browser's console as well as in the craft/storage/runtime/logs folder.


How can I create a family tree hierarchy in Craft? I'm struggling to think of a way to create a family tree hierarchy in Craft.

I've tried using categories and structures, but run into the problem of needing child nodes to have two parent nodes.

I.e.

Generally, what's the best way of achieving this?

I can't think of an easy and clean way to visualize this kind of structure in a default list. So if you want to be able to display the structure from your diagram dynamically you'll have much work to calculate the positions correctly in a clear way.

So I would suggest you to use easy Craft methods. You could create an entries field to relate your children with all the upper level parents, in your case you would have

Parent 1 - no relation
Parent 2 - no relation
    Child - related to [Parent 1, Parent 2]
        Grand Child - related To [ Child ]
    Sub Parent 1 - related to [Parent 1, Parent 2]
    Sub Parent 2 - related to [Parent 1, Parent 2]
         Grand Child 1 - related To [Sub Parent 1, Sub Parent 2]
         Grand Child 2 - related To [Sub Parent 1, Sub Parent 2]
         Grand Child 3 - related To [Sub Parent 1, Sub Parent 2]

So you can get each parent of an entry with entry.fieldHandle.find()
and you can iterate through the tree. But this will only work well when don't mix trees.. So when you have a Parent 3 and 4 with another tree like in the diagram and one of those entries can be the parent of one of the grand children in the first tree you could have trouble (performance wise) to iterate to the beginning. You can collect all parents with no problem but if you have 5+ levels you'll need many queries and it could take a lot of time in Craft2 with default ElementCriteriaModels. But that's always the case in those NxN tree connections

I don't see any issues as long as your trees are separated from each other and as long as you use custom code to fetch the entries.


Min/Max numeric search returning odd results Following on from my earlier search question...

Searching for entries across multiple fields including a relationship

I'm finding that the min/max wage search behaves oddly.

I have a range of wage values from 95 to 175.

If I search for a min of 95 with no max then I only get results from 95 up to 100.

Likewise if I search for a max value of 150 then I only get results greater than 100 and less then or equal to 150.

If I use both min and max criteria then I get no results.

I'm guessing this is something to do with variable type but can't see how I can force the variables to be integers/numbers rather than strings.

The simplified code I'm using to do the matching is:

{% set wage_from = craft.request.getParam('wage_from') ? craft.request.getParam('wage_from') : 0 %}
{% set wage_to = craft.request.getParam('wage_to') ? craft.request.getParam('wage_to') : 9999 %}

{%
  set results = craft.entries({
      section: 'vacancies',
        wage: [
          'and',
          '>= ' ~ wage_from,
          '<= ' ~ wage_to,
        ]
    })
%}

Aha! Another lightbulb moment.

The wage field was set to be plain text. I changed it to number and things work as expected.


Redirect after saveAsset in plugin I'm trying to redirect at the end of the saveasset function in init().

This is my code:

craft()->on('assets.saveAsset', function (Event $event) {

     // a lot of code here ##########################

     //#############################################

     //at the end:

     craft()->request->redirect('myurl.com');
}

When I save an asset with the redirect function at the end I get the following alert:

Upload failed for filename.csv.

The upload works when I leave the redirect out.

Thanks!

You could try to use a task, to make sure the upload is completed before redirecting.

Here is a good starting point on how to use a task:
Documentation on creating tasks

Basically you define the steps of a task, in you case I guess 2. The next step of a task is started when the last step returned true.


Profiling Summary Report in the console I've noticed a few blog posts referring to the Profiling Summary Report. In the blog posts the author shows examples of it showing on Chrome's devtools. I'm in dev mode but can't see this on my Chrome devtools. Is there some more configuration needed to show this in the newest versions of Craft?

The picture you posted is from Craft 2 when Dev Mode is enabled.  In that case, it would output the debugging and profiling information to the browser's console.

In Craft 3, that has been replaced by the Debug Toolbar.  There is a good article here on what it is and how to use it:  https://nystudio107.com/blog/profiling-your-website-with-craft-cms-3s-debug-toolbar


Multiple instances of Craft in same hosting account root I want to have multiple instances of Craft, ideally running inside the same cPanel account root.
I note from the doc on Directory structure that there are separate config path variables that can be set for:

CRAFT_CONFIG_PATH
CRAFT_STORAGE_PATH
CRAFT_TEMPLATES_PATH
CRAFT_VENDOR_PATH

If these system assets for a given Craft instance are in a per instance child folder above web root, what are the implications for the location and variants of:

modules
.env
composer.json
composer.lock
craft

Should these all be duplicated per instance into the same child folder as well?

There are various ways to go about this. Here’s a few:
Option 1: Keep each site completely contained
If you are able to keep each installation in its own directory, each with its own web root, that would be ideal, since you could develop and deploy each site individually:
site-a/
  .env
  composer.json
  composer.lock
  craft
  config/...
  modules/...
  templates/...
  vendor/...
  web/...
site-b/
  .env
  composer.json
  composer.lock
  craft
  config/...
  modules/...
  templates/...
  vendor/...
  web/...

Option 2: Share the web root
If the sites must share the same web root, but you still want to generally think of them as separate installations, then you can at least keep each of the project’s non-web files together:
site-a/
  .env
  composer.json
  composer.lock
  craft
  config/...
  modules/...
  templates/...
  vendor/...
site-b/
  .env
  composer.json
  composer.lock
  craft
  config/...
  modules/...
  templates/...
  vendor/...
web/
  index.php <-- for site-a
  ...
  b/
    index.php <-- for site-b
    ...

Then the only constant you’ll need to worry about is CRAFT_BASE_PATH. For example with the above structure, here’s what those would look like:
web/index.php:
define('CRAFT_BASE_PATH', dirname(__DIR__) . '/site-a');

web/b/index.php:
define('CRAFT_BASE_PATH', dirname(__DIR__, 2) . '/site-b');

Option 3: Share the Composer and module files, too
If it makes sense to just have one shared set of Composer files (composer.json, composer.lock, and vendor/) and modules/ folder (they are inseparable since the module files get autoloaded by composer.json), you can use this structure:
composer.json
composer.lock
modules/
vendor/
site-a/
  .env
  craft
  config/...
  templates/...
site-b/
  .env
  craft
  config/...
  templates/...
web/
  index.php <-- for site-a
  ...
  b/
    index.php <-- for site-b
    ...

You’ll need to make the same changes to CRAFT_BASE_PATH as in option 2, as well as CRAFT_VENDOR_PATH (since vendor/ no longer lives alongside the site-specific files).
web/index.php:
define('CRAFT_BASE_PATH', dirname(__DIR__) . '/site-a');
define('CRAFT_VENDOR_PATH', dirname(__DIR__) . '/vendor');

web/b/index.php:
define('CRAFT_BASE_PATH', dirname(__DIR__, 2) . '/site-b');
define('CRAFT_VENDOR_PATH', dirname(__DIR__, 2) . '/vendor');

You’ll also need to update CRAFT_VENDOR_PATH within both of your craft executables, in this case (not CRAFT_BASE_PATH, though).
site-a/craft & site-b/craft:
define('CRAFT_VENDOR_PATH', dirname(__DIR__) . '/vendor');


{% redirect "{{ entry.url }}" %} doesn't work I've set up a structure channel that has entries at /services/slug however I want the /services template to redirect to the first entry in the services structure.

What I have now is:

{% for entry in craft.entries.section('services').limit(1) %}
  {% redirect '{{ entry.url }}' %}
{% endfor %}

However when visiting /services this redirects to a 404 page with url of /%7B%7B%20entry.url%20%7D%7D/

I also tried {% redirect "services/{{ entry.slug }}" %} but that didn't work either.

Is it possible to set up a redirect in the way that I am trying to do here?

You do not use the {{ }} inside other brackets you also should not use ' ' unless it is a specific string you want interpreted. Try instead:

{% for entry in craft.entries.section('services').limit(1) %}
     {% redirect entry.url %}
{% endfor %}

And you should be good to go


"Email" Control Panel Settings page is blank I'm currently unable to access my 'Email' control panel settings page. When the page loads it's completely blank, and the body of the response is simply the scripts that log the Application Log and Profiling Summary Report to the console.

Every other settings page works fine.

I've tried disabling all plugins (currently just one), but this did not have any affect.

Craft is up-to-date as of today at 2.6.2967.

I was able to resolve the issue by downloading the latest version of Craft CMS and replacing my existing /craft/app directory with that latest version (as outlined in the Manually Updating section of their documentation).

I was previously using the One-click Updating method in the control panel, so I'm not exactly sure of the original cause of the issue.

Thanks to Brad Bell for the help!


Is it possible to have one Craft install running Can a Craft install run on multiple domains and/or subdomains?

For example having the same Craft install running a blog Channel at blog.example.com and also an about Single at example.com

Sure it can. Craft 3 has multi-site support.
And for using a subdomain, you don't even need that, just point that subdomain at the correct template URL (eg. forward blog.example.com to example.com/blog).
The about single at example.com would just be your homepage.


Craft CMS/Feed Me slow performance I am wondering if I have structured my data badly and was hoping someone could advise on an alternative. Essentially I have a structure with two types, a catalogue and the catalogues children. Some catalogues may have up to 400 children.

When I began importing the data using Feed Me I didn't have any problem, but after a while it was becoming nearly impossible to use and I'm only half way through. I checked the logs in the debug bar and found this was holding things up. Perhaps it's of some help?

Any advice here would be really appreciated!

Edit:

For more clarification, this log is from the screen where you map the fields. There may be around 15,000 entries so far, most of which are the children entries. I am just wondering if there is something wrong with using structures this way or is this just because of the large amount of entries in the database? I have read that people are running Craft sites with over 100,000 entries so I didn't think this would be a problem.

I would recommend running the Craft queue in a background process as detailed here. This way it won't bog down your control panel and can just chug away in the background.


Prevent caching from inside of the cache tag Does anybody know, if it is possible to prevent caching from within the cached code/content?
Something like:
{% cache ... %}
...
{% do notCache %}
...
{% endcache %}

Why? Because if there is a content builder inside of the cache tag, certain content elements could simply disable caching that way by calling  {% do notCache %}

No you can't, but you might be able to cache each block individually rather than trying to exclude one of them.


How to create a simple widget? I have limited knowledge of PHP but I would like to try and create a widget. Basically all it needs to do is provide some text and a link to the user profile page as you can't route directly to that page on login. Would someone be able to point me in the write direction please. I have in my grWidget.php file:

<?php

namespace Craft;

class GrWidget extends BasePlugin
{
  function getName()
    {
      return Craft::t('Gareth Widget');
    }

    function getVersion()
    {
      return '1.0';
    }

    function getDeveloper()
    {
      return 'Gareth Redfern';
    }

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

I think you are mixing up your Primary Plugin Class with your Dashboard Widget.

Plugin Structure:

Assuming your plugin is called Gareth and your widget Gr, this files should be in your /craft/plugins/gareth/ directory:

GarethPlugin.php
templates/

GrWidget.html

widgets/

Gareth_GrWidget.php

Primary Plugin Class: GarethPlugin.php

  Your primary plugin class defines all of the things that Craft needs
  to know about your plugin, such as the plugin’s name, version number,
  developer’s name and URL, and Global Settings.

<?php
namespace Craft;

class GarethPlugin extends BasePlugin
{
    function getName()
    {
         return Craft::t('Gareth');
    }

    function getVersion()
    {
        return '1.0';
    }

    function getDeveloper()
    {
        return 'Gareth Redfern';
    }

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

Widget Class: Gareth_GrWidget.php

This class defines the widget types name getName() and its content getBodyHtml().

<?php
namespace Craft;

class Gareth_GrWidget extends BaseWidget
{
    public function getName()
    {
        return Craft::t('Gr');
    }

    public function getBodyHtml()
    {
        return craft()->templates->render('gareth/GrWidget');
    }
}

Widget Template: GrWidget.html

This is just some text which will be shown inside the GrWidget.
A link to my user profile

Result:

More:

Check out the Widget documentation. Also take a look at Craft's default widgets which can be found in the craft/app/widgets directory.


Upload an asset in a custom form I am trying to upload/add an asset to an entry via a form on the website. The entry saves fine when I don't include the asset field but as soon as I add the asset field and try to upload a file I get this odd SQL error.

  CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (housewares.craft_relations, CONSTRAINT craft_relations_targetId_fk FOREIGN KEY (targetId) REFERENCES craft_elements (id) ON DELETE CASCADE).
  The SQL statement executed was: INSERT INTO craft_relations (fieldId, sourceId, sourceLocale, targetId, sortOrder, dateCreated, dateUpdated, uid) VALUES (:row0_col0, :row0_col1, NULL, :row0_col3, :row0_col4, :row0_col5, :row0_col6, :row0_col7). Bound with :row0_col0='4', :row0_col1='27', :row0_col3='Golfclubs.jpg', :row0_col4=1, :row0_col5='2014-09-03 23:36:06', :row0_col6='2014-09-03 23:36:06', :row0_col7='a1e565e1-f6d3-4f3b-8a6f-2c049d236b13'

The field works fine in the CP.

This is the field

<input class="form-control" type="file" id="image" name="fields[image][]" />

Any ideas?

Problem solved! (head slap)

The <form> requires the following parameters:
enctype="multipart/form-data"

An odd error that gets thrown if omitted.


How can I let the user activate a particular SuperSort filter ***I have just realised I am mixing up my filtering and sorting. I have amended the question to try and make it a bit clearer.

I'm trying to use SuperSort plugin to run different filters, but I'm struggling as only the last filter gets applied. I would like to add the filter to a button or link, so that when the user clicks on it, it activates the filter. Any tips?

search

<form action="{{ url('search') }}">
    <input type="search" name="q" placeholder="Search">
    <input type="submit" value="Go">
</form>

{% set query = craft.request.getParam('q') %}
{% set users = craft.users.search(query).order('dateUpdated')|reverse %}

{% if users|length %}

        <span{{ users|length }} results:

A-Z

Z-A

Nearby

Newest

Oldest

{% endif %}

For example:

link#1 - sort A-Z
link#2 - sort dateUpdated

So in order to do this you have to reformat your code and your strategy a bit. You cant provide a Craft query as a link, all that does is grab an array from the database and it won't inherently print something out.

A-Z

The best way to change the way your results are being sorted (if you want to do it via Twig and not something front-end like JS is to send the sort style through a query string.

So let's assume you are returning a list of users and you want to sort them by first name alpha ascending:

{% set users = craft.users.order('firstName asc').find() %}

If you want to change the direction of the order create a link like this:

Sort Z-A

When the page reloads a new query parameter is available to you sort, you can get it with this code:

{% set sort = craft.request.getParam('sort') %}

Now you can use that variable to alter the way your original query works. Something like this... starting over from scratch:

{% if craft.request.getParam('sort')|length > 0 %}

    {% set sort = craft.request.getParam('sort') %}

 {% else %}

    {% set sort = 'asc' %} {# default sort #}

 {% endif %}

Then in the Craft query, you could just user this instead of our original query above:

 {% set users = craft.users.order('firstName ' ~ sort).find() %}

Now when the page first loads you will get users sorted by firstName asc and when you click the filter it will reload with firstName desc.

You can apply this same query string method to all of the parameters. Getting variables like:

{% set sortBy = craft.request.getParam('sortBy') %}

Where sortBy equals firstName or lastName

That query string would look like:

url/user-list?sort=desc&sortby=firstName

And so on.