How do I set Redactor formatting button to wrap selected text in two tags? ... Is it possible to set Redactor button to wrap my code snippets inside two tags?

...

This is what I have so right now.

formattingAdd: [
    {
        tag: 'code',
        title: 'Code Inline'
    },
    {
        tag: 'pre',
        title: 'Code Well'
    },
    {
        tag: 'mark',
        title: 'Marked'
    }
]

But some scripts and Bootstrap wants it wrapped in both of the tags.

If it were me, I'd try to keep as much formatting cruft out of a wysiwyg as possible, it cleans things up down the road and keeps your content as structured as possible. If you ever change frameworks or anything else, that extra cruft can come back to haunt you because it's all stored in the database.

A better way is handle this with a couple Matrix blocks. Set one up for text, and then another one for code snippets. Then in your template when you want to spit out a code snippet, you just wrap it using whatever extra bits you need like:

{% for block in entry.myMatrixField %}

{% if block.type == "text" %}
    {# handle text #}
    {{ block.entryText }}

{% elseif block.type == "code" %}

{{ block.codeBlock }}

    </div.

{% endif %}

{% endfor %}

The upside here is that it's all built-in, you don't have to modify any redactor defaults to make this work. But the bigger upside is if let's say you're building a library of code snippets, it'd be super easy to query the Matrix fields and get just those snippets you want.

You could even completely reformat the page and just show the code snippets, since you have them already broken out.

IMO that's what makes Craft so powerful, it's easy to use more structured data unlike other solutions *cough* like WordPress *cough* that put everything in one "field."


User photos not showing after replacing photo I recently updated some of the photos for a user group. I'm using the default user photo field.

I'm displaying the user photos on the front-end of my site and the images were displaying just fine. After replacing the images the image tag on the front-end of my site is showing a broken image. If I view the image tag src it points to the old image filename, not the updated file's filename.

I have cleared Craft's cache.

How I can make getPhotoUrl() use the new filename?

Can I ask why you can't change the filename to the old one? For the new file that is. That will easily solve the problem.

The reason it won't show up as per the new file name is that when you upload a profile photo for a user, craft creates a image model for it and when copying over a file directly this image model will not be created hence you either need to use the backend for uploading profile photos or change the filename to the old one. Also you would need to do this in multiple folders as inside userphotos/{username}/ you will see that there are multiple folders, these are folders for different cropped sizes of the profile photo and will be displayed in different locations, Hence you will need to replace the file in all of these locations for the user photo to appear correctly in all places.


Color Picker with "no color" option? I want let the editor to choose an optional color via the color picker, but this didn't have the option 'no color' (or transparent).

Is there a solution to this? I use it a lot and have always to add a boolean switch so the editor can switch it on and off, but that's not the best way to do this.

At the moment there is no better solution for this. You could write a plugin that defines a new fieldtype.


Asset with related entry field in Matrix block I have an Asset source "Image link gallery" with two custom fields for each Asset: "image title" (text field) & "Image link" (Entries field - can link to multiple sources).

I have a Matrix block "Image link Gallery" with an Assets field "Images" which selects from this Asset source.

I want to be be able to select a bunch of images and return the image, title, and link to the entry.

{% for imageItem in block.images %}

        {{ imageItem.imageTitle }}

{% endfor %}

This is returning all the images and titles but no links.

Where am I going wrong?

You said it yourself, the problem is that an Entries field can link to multiple targets. So it is an array of Entry Models you're given here, or more correctly, an ElementCriteriaModel.

To get the first linked entry's Url, all you have to change is to add the first method.

But you said multiple links are allowed, so to show them all go through them in a loop.

{% for imageItem in block.images %}
    {% for linkedEntry in imageItem.imageLink %}

            {{ imageItem.imageTitle }}

    {% endfor %}
{% endfor %}


Unable to render a plugin template Creating a plugin that contains a custom field. I need to have some custom html for the settings of the field. I have the following in my field class:

/**
 * @inheritdoc
 */
public function getSettingsHtml()
{
    return Craft::$app->getView()->renderTemplate("src/templates/settings.html", [
        'field' => $this,
    ]);
}

I have a "settings.html" in "src/templates".

What am I doing wrong?

Please read the docs (or this) about how to render plugin templates. It's all well explained there . You don't need to define src/templates but your plugin handle

`plugin-handle/settings.html`


Lots of 404 Page Errors Does anyone know why Craft CMS generates continual 404 errors for things like the following:

?p=1504
tag/tag.js
newsdetail.asp?
module/mod_novasfh?

Even after clearing or 301 redirecting 404 errors, a few days later, they explode again and create hundreds of errors in Search Console/Webmaster Tools

Where are the links coming from? A Template?

"?p=1504" should not 404, if it's attached to the end of an existing "200" url.

Do a crawl with an app called "Screaming Frog" to determine where your 404s are actually coming from then you can fix in your templates.

Sounds like your just sweeping the actual problem under the carpet and not fixing the source of the problem!


Implementing two factor authentication / TOTP for CP logins We have a client with fairly extensive security requirements. They have asked us if it is feasible to implement something like Authy in Craft.

I'm provisionally planning to disable the "normal" CP login form and implementing a new login flow via a plugin that checks the OTP first and then hands off to UserSessionService for the actual login. Is there any reason that wouldn't work?

If it will, what's best way to effectively disable the default CP form and direct users to the plugin's form instead?

Lastly, are there any gotchas that I should look out for in terms of maintaining as close to "normal" Craft behaviour as possible.

PS I know there's the userSession.onBeforeLogin event, but unless I'm missing something, that looks fairly limited (only receives the username of the User as a param etc)

I know this is a little late, but i've just build a plugin for TOTP. It is in beta, so beware before using it in a production environment.
https://github.com/born05/craft-twofactorauthentication


Find specific image from global image set? I am using a global set to store image assets used across the site.  I am not sure how to reference a specific image. I know how to get the image if its just one, using :

{{ design.imgs | length ? design.imgs.first().getUrl() : '' }}

What if there are several images and I am looking for a specific one?

When you call myGlobalSet.myAssetsField, you're creating an ElementCriteriaModel. This is significant, because an ElementCriteriaModel is basically a "search object".

Your design.imgs call produces an ElementCriteriaModel based on craft.assets. It will return only the assets which are related to your global field.

You can manipulate your ElementCriteriaModel in whatever way you want!

{% set myAsset = design.imgs.kind('image').sourceId(1).first %}


Commercial Plugins and Solo Licensing? Brand new Craft user.  Second day playing with it, and so far, loving it!

I believe the Solo license allows a Freelancer to roll off personal (for her own use) implementations for free -- even if those sites have a commercial purpose.

I understand this to mean I may power more than one site for free under the terms of the Solo license.

Question: Does this Solo licence freedom extend to paid plugins?

For example, I want to purchase the commercial Enupal Backup plugin.  I would like to use it on my two Solo-licensed Craft websites.  Can I do it, or must I purchase the plugin twice?

Technically, that's up to each individual plugin developer. But realistically, the vast majority of commercial plugins are only valid for a single site.

If it's a paid plugin, you'll probably need to pay for it on each site independently.

  "I may power more than one site for free under the terms of the Solo license."

It's important to realize that you're actually working with multiple licenses in this case... they just all happen to be Solo (aka free). Each site has its own license, you are not sharing a Solo license across multiple sites.


Sprout Forms: empty phone field still shows error "Phone is invalid. Example format: (506) 234-5678" Running Craft CMS 3.3.20 and Sprout Forms Pro 3.6.8

form has Phone field
submit form with no value in Phone field
form reloads with error message "Phone is invalid. Example format: (506) 234-5678"

If valid phone number entered form submits fine.

This was a bug and is resolved in release Sprout Forms v3.6.9 and Sprout Fields v3.5.2.

Original Reply:

  This is a bug in Sprout Forms v3.6.8. We'll have a fix out for this shortly and I'll update this comment when we do.


CSRF Token not verified with actual gateway in Craft Commerce My payment page form works just fine with the dummy gateway, but once I change it to use my authorize.net gateway it says that the CSRF token isn't verified. The code below isn't complete, but I figured maybe there is something in this part that is causing it? Any ideas would be great, thanks!

<form class="flex-container flex-center flex-col nav-buttons flex-lg" method="POST">
  {{ getCsrfInput() }}
    <input type="hidden" name="action" value="commerce/payments/pay"/>
    <input type="hidden" name="redirect" value="/store/customer/order?number={number}"/>
    <input type="hidden" name="cancelUrl" value="/store/checkout/payment"/>
    <input type="hidden" name="paymentMethodId" value="1"/>

{% set formValues = {
    firstName: paymentForm is defined ? paymentForm.firstName : (cart.billingAddress ? cart.billingAddress.firstName : ''),
    lastName: paymentForm is defined ? paymentForm.lastName : (cart.billingAddress ? cart.billingAddress.lastName : ''),
    number: paymentForm is defined ? paymentForm.number : '',
    cvv: paymentForm is defined ? paymentForm.cvv : '',
    month: paymentForm is defined ? paymentForm.month : 1,
    year: paymentForm is defined ? paymentForm.year : (currentYear +1),
} %}

Welp... I feel like an idiot. It wouldn't let it through because I didn't set the endpoints found at https://craftcommerce.com/docs/payment-gateways


Commerce plugin in Craft 3? I am looking at Craft Commerce (https://craftcommerce.com/) and I am wondering if anyone has any experience using this in Craft 3? Seems like it is only for 2.x for now.  I am struggling to find any information on a Craft 3 release for Commerce.

We haven't given a hard date for the official release of Craft other than before the end of the year.

A Craft 3 compatible version of Commerce (Commerce 2.0) will be released at the same time Craft 3 is officially released.


FreeForm: Adding attributes to the honeypot field I'm using VueJS too process and submit forms, and I would like to utilize the freeform honeypot functionality. The issue is that I am unable to add a v-model attribute to the honeypot field.

I've already got the CSRF token passing into the VueComponent without issue; I need to get an attribute onto the honeypot field.

Is there a way to do this out of the box?

It looks like this isn't something that's currently possible. The code that generated the honeypot field isn't able to be extended vendor/solspace/craft-freeform/src/Services/HoneypotService.php::240

I ended up doing some js magic, like this:

if(this.formHoneypotName) {
    let stickyFingers = form.target.querySelector('#' + this.formHoneypotName)
    params.append(this.formHoneypotName, stickyFingers.value ? stickyFingers.value : '')
}


An error occurred when rendering a template I have an odd problem.

When I render a simple HTML template without any link to the Control Panel, I get the following message on random pages:

  An error occurred when rendering a template

Whenever I change I can't seem the remove this error or find the problem / solution.

Also I cannot access the Control Panel.

Can you please help me?

Thanks!

You can receive this error if you have uploaded a Craft website and your craft/storage/runtime/cache and craft/storage/runtime/complied_templates folders are not writable.

We made these folders writable and resolved the error.


Multi-lingual site navigation made of singles, channels and structure Does anyone have any examples of how they've put together the main site navigation for a multi-lingual site set-up made up of singles, channels and structure?

At the moment I've just hard-coded the nav and done and if else on the locale ID but would like to know if there's a more flexible, future-proof method.

I have one main structure "pages" and got rid of all single sections. I also gave each channel's index page an entry in the structure (good for URL translation). Then I added some entry types to it (you can also link templates to them) and created my site navigation like in my example code below.

This allows you to translate the slug of the index pages in the CP and you have access to localized URL (page.getUrl) and page title variables (page.title) in your nav template.

Only one level of hierarchy I need. If you have to go deeper, the nav tag's waiting for you! ;)

{# Get top-level entries in pages structure #}
{% set pages = craft.entries.section('pages').level(1) %}

        {# Loop through entries (= pages) and list the links #}
        {% for page in pages %}

                {{ page.title }}

        {% endfor %}

        {# Include links to switch locales #}

            {% include '_includes/language_switch.html' %}


Can a non-admin add Entry types into a section? Is there a way to allow a user to edit sections without making them site Admins? For example, I have a couple of users that I want to allow them to create new entry types within a Channel, but I don’t want them to be able to access the rest of the Settings section of the CP or do everything an Admin can do.

I'm guessing this is something that will require a custom plugin, but is it possible to sidestep the admin permissions to create new entry types?

You would have to write a custom plugin that provided its own UI (outside of the Settings portion of the control panel) and that plugin's controller could mimic Craft's SectionsController (with the exception of not requiring an admin) while calling SectionsService's saveEntryType.

For security your plugin should also register a custom "canSaveEntryType" permission so you can have fine-grained control over who can call that method.


Custom fields on a structure or section archive page I have a section (or structure, works both) for "events". On the archive template (see image below) I want to add a custom image in the header. The administrator needs to be able to upload the header image.

In a section/structure there is no dedicated page, so I cannot assign custom fields to it. How do I tackle this problem?

What you could do is make a "Global" Which sets the header image. You could name the global something like "Event Page Fields" or something like that so its clear for your administrator where to look.

The other option is creating a Single page and load all the structure items via the template there. This way you can add the image field to that single.


Error when Attempting to Install Plugins I keep getting this error whenever I try to install a plugin.

Not sure how to troubleshoot / resolve this.

Basically, I need the Contact Form and CKEditor plugins.

Setup: I'm running AMPPS with PHP 7.1, Apache and MySQL.

I don't really know what is causing this error but I've got the same problem for plugins install and update. To avoid this annoying error page, I prefer to install/update plugins via composer.

composer update

or

composer require {plugin name}


Direct link to form using freeform We have a form on our website that helps us build subscribers organically. But, we'd like to be able to share a direct link to our subscribe form so that we can do direct outreach to gain subscribers. Does freeform allow you to access the form directly via a url?

The short answer is no... but that kind of thing is not really Freeform's responsibility - Craft gives you the flexibility to output whatever you want wherever you want, but in order to do so you need to create templates and/or routing to suit your requirements.


Craft CMS - Dynamic Order Field Layout In Sections I'm wanting to have the order of my elements within a template dynamic so that the user whilst in a template of page can reorder the modules as they please.

See screenshot for example

Within the entries of the home page where I am editing content, could I reorder the "Hero Detail Body" to appear above the "Hero Detail Heading"?

My initial thoughts were no as within the Sections site, the components display order are defined for the template / tab there.

Is this possible?

Correct, there's no way out of the box to reorder fields on the fly in the Entry editor. If you're comfortable with Craft plugin development though I'm sure it's possible to extend Craft and add the ability to do what you want to do. It's also possible that someone has already developed a plugin that achieves this but I personally don't know of any off the top of my head.

However, it seems in your case that if you want to be able to rearrange fields in the Entry editor, your best solution is to put those fields inside a Matrix field. When you have created several fields inside a Matrix field, those "sub-fields" are then arrangeable in whichever order you prefer in the Entry editor. If you've never used Matrix fields before, here's the documentation link so you can read up on it: https://craftcms.com/docs/matrix-fields

Another alternative would be to use the Neo field - if you decide to use Neo, you can just reference your currently existing fields and then add only the Neo field to the page.

Hopefully that helps to answer your question. Cheers!


Filtering values from Twig for my custom field type I have a custom fieldtype for Craft which stores its value as an array of Models using AttributeType::Mixed. See below for an example of the FieldType and Model setup

class MyCustomFieldType extends BaseFieldType
{
    public function defineContentAttribute()
    {
        return AttributeType::Mixed;
    }
}

class MyCustomModel extends BaseModel
{
    protected function defineAttributes()
    {
        return array(
            'url'      => AttributeType::String,
            'category' => AttributeType::String
        );
    }
}

Then when the value is persisted, it's saved as an array, which Craft natively saves as JSON

$values = [new MyCustomModel(), new MyCustomModel(), ...];

To display the value in Twig I can do something like

{% for item in entry.myCustomField %}
    {{ item.category }}
{% endfor %}

My question is, how can I only display the elements in my field which have a specific attribute value? For example, if I wanted to display only those items with a category of main, where 'category' is an attribute on my model?

{% for item in entry.myCustomField.category('main') %}
    {{ item.category }}
{% endfor %}

Would this help?

Filter Entries by Field Value

Than it would be something like this I suppose (never used it myself):

{% for item in entry.myCustomField.search('category':'main') %}
    {{ item.category }}
{% endfor %}


Using Asset Field in a Template I'm confused about how to use an uploaded asset in a template (or rather why it isn't working).

1) I create an asset source and folder (Note: I did not add any fields).

2) I added this as a field in my entry fields called heroImage

3) I uploaded an asset to my single entry for the page.

4) I added this to the template

{% for asset in entry.heroImage %}
             {{ asset.url() }}
             XXXX
{% endfor %}

5) I also tried

    {% set assets = entry.heroImage %}
    {% if assets | length %}

Some great assets

      {% for asset in assets %}
          {{ asset.url }}
      {% endfor %}

    {% endif %}

I can see the image on the entry page but the template wont render it.

What could be

Unless I'm misunderstanding the question, surely you'll need to use an IMG tag?

{% for asset in assets %}
    <img src="{{ asset.getUrl }}" />
{% endfor %}


List out all "Layout Tabs" in the frontend I have a few tabs in my "Field Layout Design", and I wondered if there was a way to list the titles of each one, in the frontend? Something basic like:

Services

Testimonials

Gallery

Thanks :)

Assuming you have an 'entry', this should work:
{% for tab in entry.getFieldLayout().getTabs() %}

{{ tab.name }}

                {% for field in tab.getFields() %}

{{ field.name }}

                {% endfor %}

{% endfor %}

if you don't need the fields then just:
{% for tab in entry.getFieldLayout.getTabs() %}

{{ tab.name }}

{% endfor %}


Search only in entries with own urls checked Is it possible to search only in entries that have the own URLs option checked.

Now i've this code:

{% set query = craft.request.getParam('q') %}
{% set queryWords = query|split(' ') %}

{% paginate craft.entries({
    search: queryWords|join(' OR '),
    subLeft: true,
    subRight: true,
    order: 'score'
}).id('not ' ~ entry.id).limit(10) as pageInfo, items %}

Got this solution from Andrew Welch/nystudio107 over on Discord:

Query for ':notempty:' in the URI, for example:

craft.entries().uri(':notempty:').all()

Docs: ':empty:' and ':notempty:'


User permissions on a per-entry basis? I have a Structure section that contains most of the pages on my website.

We have users that need to edit only some of those pages. Since permissions are set on a per-section basis, right now they can edit either all or none of those pages.

How would I go about building custom user permissions for only some of those pages?

This might be considered more of a "workaround" than a technical solution, but I think it could actually solve your problem quite nicely...

You can use CP CSS and/or CP JS to show or hide certain fields.

You'll probably find that the CP Body Classes plugin is helpful for narrowing in on specific conditions. For example, you could show/hide certain fields based on a specific user group.

Disclaimer: I wrote each of those plugins. Feel free to leave feedback on Github!


When should I log in a plugin? With regards to logging in your own plugin, is there a point which could be considered "You are logging too much" For example. In a service I currently have something like this:

public function getSomeRecordsByParentId($id)
{
  FooPlugin::log(Craft::t("Getting all records for parent id {$id}"), LogLevel::Info);

  // .. do service logic here

  FooPlugin::log(Craft::t("Found {$recordCount} records for parent with id {$id}"), LogLevel::Info);
}

And then again

public function getRecordById($id)
{
    FooPlugin::log(Craft::log("Trying to find record with an id of {$id}"), LogLevel::Info);

    $record = FooRecord::model()->findByPk($id);

    if(!$record)
    {
        FooPlugin::log(Craft::log("Unable to find record with id {$id}"), LogLevel::Error);
        throw new HttpException(404);
    }

    return FooModel::populateModel($record);
}

I know I'm only doing two per function at the moment but when they are all called it can really start to stack up.

I guess what i'm asking is are there any real performance hits that are going to be noticeable or has anyone noticed anything from logging a lot of things?

A few things to keep in mind.

LogLevel::Infois only going to be logged when devMode is enabled, so any overhead from excessive logging won't be an issue in production.
Excessive logging will consume extra memory because all logging information on a given request is stored in memory and flushed to disk at the end of the request, but overall I imaging that the performance hit will be negligible.
Excessive logging will cause your log files to rotate out quicker.  By default Craft will cap each log file at 1MB worth of data and will start to rotate out the older files after 6MB worth of data has been hit.


Craft Commerce hasStock not working? I'm trying to query for certain products but only ones that have stock (the products just have defaultVariants):

{% set earliestDate = now | date_modify('- 1 days') %}
{% set latestDate = now | date_modify('+ 10 days') %}
{% set products = craft.commerce.products({
    hasVariants: {
        hasStock: true
    },
    type: 'class',
    date: 'and, > ' ~ earliestDate ~ ', < ' ~ latestDate,
    order: 'date',
    limit: 5
}) %}

The above returns 5 products, all of which happen to have no stock left as identified by them not showing when I use:

{% if product.defaultVariant.stock > 0 %}
    {{ product.title }}
{% endif %}

I'm currently getting products to show by setting the limit to 25 and then it only shows 1 product in stock. Meaning the query is returning 25 products, of which 24 have no stock so shouldn't be returned.

Running Craft Commerce 1.2.1337 so am up-to-date.

Could be related to: Commerce products returning different results on page load

Someone else mentioning it in comment to answer of this: How do I check if a product has stock in any of it's variants?

Your product element criteria is using a condition param: hasVariants, but it should be hasVariant as per the docs: https://craftcommerce.com/docs/craft-commerce-products#hasvariant

That correctly only returns products (where a variant that belongs to that product) is in stock.


Need to implement quiz feature I need to implement quiz feature in which a few questions will be asked to user.

Could anyone please let me know if there is any plugin for it.

Until the plugin store arrives, the complete list of available plugin is here:

  http://straightupcraft.com/craft-plugins

I don't know of any quiz plugins specifically. I did build a rudimentary quiz for a client, using only a matrix field. Depending on how you wanted to architect your quiz, a plugin may not even be necessary.


AttributeType::Handle Validation and Unique I'm building a plugin that has a column in the DB which is unique and essentially an AttributeType::Handle.

Here is the piece from the record:

return array(
    'key' => array(AttributeType::Handle, 'default' => '', 'required' => true),
);

And in my service after the $model has passed validation:

if ($record->save()) {
    // update id on model (for new records)
    $model->setAttribute('id', $record->getAttribute('id'));
    return true;
} else {
    $model->addErrors($record->getErrors());
    return false;
}

When does that handle validation happen? If I pass something that wouldn't pass handle validation (spaces or a reserved word), it doesn't save the record in the database, but it doesn't throw any errors.

In addition, is there a way to throw an error when the value isn't unique? Again, the record doesn't save if I use a key that is already in the DB, but there is no error.

Happy to provide more code if necessary, just didn't want to overcomplicate the question. Thanks!

In addition, is there a way to throw an error when the value isn't unique? Again, the record doesn't save if I use a key that is already in the DB, but there is no error.

If you use 'unique' => true in an attribute on your record, Craft will use Yii's CUniqueValidator class to verify the uniqueness of an attribute in the database.

$record->validate() will fail and you can use $record->getErrors() to get the error message.

return array(
    'key' => array(AttributeType::Handle, 'default' => '', 'required' => true, 'unique' => true),
);


How to auto enable a plugin after install? I am developing a plugin for craft 3 and the plugin just got published to the store.
I can browse through the store and install the plugin but it stays disabled. The user will have to goto Settings -> Plugins and then manually enable the plugin even after installing. Is there a way to auto enable the plugin after install?

It's because the plugin is doing this in the init():
https://github.com/poptins/craftcms-poptin-app/blob/master/src/Poptin.php#L69-L74
That's basically overwriting Craft's default Project Config settings for a plugin (which is to be enabled).
https://github.com/craftcms/cms/blob/develop/src/services/Plugins.php#L536-L545
If you keep it there, then you'll have to explicitly set it to enabled in Project Config as well, but ideally, you'll want to move that logic out of init() and into something like an EVENT_AFTER_INSTALL_PLUGIN event.


Missing "Plugin Store" navigation on Craft 3 admin section I am a newbie to CraftCMS and just installed my very first Craft Project on local Xampp. Everything looks good except the "Plugin Store" navigation menu is not showing up. Is there any trick or tweak to appear the default menu?

Thanks in advance!

Here's the screenshot

You need Craft 3 for that. Looks like you are on version 2.7.4
The link provided gives information about new features in version 3, among them being the Plugin store.


How can I pass a JS result into a Twig template? I've got a frontend form which queries the openstates.org API to return a given set of data objects.

Those objects also exist in Craft as entries, and the API data includes a field that serves as a unique ID for the Craft entries - how can I pass those unique IDs back to the Craft template to retrieve the corresponding entries?

Per Michael's suggestion above, with some help from this answer, I passed the results from the API call back to a craft template as query params, so it looked like this (simplified):

{% if craft.request.isAjax %}
    {% set myReps = craft.request.getParam('personId') %}
    {% set myIds = myReps | split(',') %}
    {% for myId in myIds %}
        {% set person = craft.entries.section('representatives').repId(myId).first() %}
    {% endfor %}
{% endif %}

and then output my info from there.


My site is down and I can't access the admin panel after attempting an automatic update I attempted to update my website by pressing the update button in the control panel. It failed and now site is down. How do I fix this? I don't have a backup to restore.


Custom upload plugin to unzip files I need to build a plug-in. Actually I've built half of the plug-in already but I am questioning my approach. I wanted to get another point of view to see if I'm headed down the wrong path.

In my Craft control panel I want to be able to add a ZIP file to an entry or just into Assets directly. In an entry I can currently do this through an Assets field type. But I need to extend the functionality because I need to do some file validation on the zip file and then unzip it and then validate the contents of the unzipped content as well. Finally I then need to have the ability to reference the folder that contains the unzipped files.

In more concrete words, I want to be able to upload a zip file that contains an animated advertising banner. As an example, the zip file would be named "acme_banner_300x250.zip". Uploading that file would check that the banner dimensions are stated in the filename (300x250) and that the contents of the ZIP include an "index.html" plus it must contain an image file with the word "backupImage" in the file name. If all those things are true, it would unzip the file and then delete the original ZIP.

Finally, when this asset is included in an entry, I want to be able to pick it from the asset list (where it shows the backupImage file from the zip as the thumbnail) and have it be able to report the proper height and width properties along with a 'url' property that points to the folder containing the index.html file.

(Side note: These are all files I've built myself so I am not worried about malicious content being included in the upload, although if there is a way to scan them for malicious content, that would be good with me.)

My current half-finished plug-in does the following: It will intercept an uploaded asset using the "assets.onBeforeUploadAsset" event listener and then unzip the file (if the extension is "zip") in a location I can designate. I'm left with the original zip file in the Assets listing and I'm struggling with how to use the unzipped directory in my entry because that unzipped location isn't associated with the zip file listed in my assets.

I'd like to select whether this whole process happens or not. Right now, any ZIP file gets unzipped and I would prefer to be able to upload a ZIP file and have it remain a plain old ZIP file sometimes (i.e. when a client needs to get a ZIP of files from me).

Am I going down the wrong path trying to work within Assets to build this functionality? It feels like I'm creating a new type of Assets rather than just working within the existing Assets available file types.

What you could do is to create a new asset source and a new asset field for the backupimage and a plain text field for the HTML (you can later convert this to an Incognito field). Add those new fields to the ZIP files' field layout.

After unzipping the bundle to a temp directory with you plugin, you can now check if the files meet your requirements. If everything's fine, create an asset file model from the backupimage using the insertFileByLocalPath method and relate that asset to the ZIP asset by storing its ID to the ZIP's backupimage asset field. Now read the HTML file and store it into the ZIP's html plain text field.

You might also want to have a look at the source code of my Asset Metadata plugin, as I'm doing some quite similar things with the field type it provides.


Entry view count in the last 24 hours I'm working on a typical craft blog with articles. I know there is a plugin that was used to teach craft plugin development that tracks entry visit counts here:

https://straightupcraft.com/craft-plugins/entry-count

However, is there anyway to distinguish the visits made in the last 24 hours? The docs on this simple plugin doesn't talk about it. The logic would probably be take the view count now and subtract by the count from 24 hours ago. I'm guessing the view count might be a value in the mysql table that keeps getting updated. If each count is a row in the table then perhaps there are ways to just query the db for counts associated with an entry filtered by the time stamp. But I highly doubt thats how the plugin is implemented.

I also could use help tracking the posts with the highest upvotes using the upvote plugin:

https://straightupcraft.com/craft-plugins/upvote

I'm doing this to work out a trending logic. Trending posts are posts that have a combination of highest view count and upvotes in the last 24 hours.

It looks like the Entry Count plugin could potentially serve your needs, though you'd need to make a few changes for it to behave the way you want. Natively, it looks like the counts are just lumped together for each entry.

Upvote is perfect for checking recent votes! (Disclaimer: I'm the author of Upvote.)

With Upvote, you can see if an entry was voted on in the past 24 hours, simply by checking the craft_upvote_elementtallies.dateUpdated value in the database.

If that's not detailed enough, you can enable the option to "Keep a detailed record of all votes". This gives you a vote-by-vote report of every single upvote/downvote ever cast. The detailed log is stored separately in the craft_upvote_votelog table.

  Warning: An unchecked craft_upvote_votelog table can grow rapidly, and quickly swell the size of your database. If you only need it to check up on recent votes, feel free to set a cron job to frequently delete old rows.

The craft_upvote_votelog table is not critical for the day-to-day operations of Upvote. It's more of a "nice to have" for rare situations which could benefit from it (like in your scenario).


CraftCMS Push Notifications: New Device Token I've been looking at the Push Notification Plugin.

Link: https://github.com/boboldehampsink/pushnotifications

I'm having some issues determining how an iOS or Android application can automatically add a new device token to an application. Meaning, I wouldn't want to add the device token via the CP. Most users don't know what their device token is.

I've looked at the HTTP Requests that is produced when I click to create a new device in the plugin settings; however, when I test trying to create a new device only by URL it fails. Any ideas?

Has anyone else used this plugin?

I have finally figured this out with the help of the developer, boboldehampsink. Thank you so much for your help!

The post parameters are:

{
    'app': 'app_handle',
    'platform': 'ios/android',
    'registrationId': 'token'
}

Note:

You must use the front-end url to register a device without needing login credentials.

Post to the URL:
http://localhost/CraftCMS/public/actions/pushNotifications/devices/registerDevice

More information found here: https://github.com/boboldehampsink/pushnotifications/issues/1


PSR-0 Composer Autoloading causing class not found in plugin I have composer setup at the root of the plugin folder with a few dependencies. I have custom classes in a folder at root we can call pluginX, I am autoloading its namespace with composer like such.

{
  "autoload":{
    "psr-0": {"PluginX": "PluginX/"}
  },
  "require": {
    "andrefelipe/orchestrate-php": "0.14.0"
  }
}

however when I try and use my class which resides at "PluginX/Models/Trips" like below I get a "Fatal Error: Class Not found..."

<?php
namespace Craft;

use \GoWander\Models\Trips;
use \andrefelipe\Orchestrate;
use \GuzzleHttp\Client as GuzzleClient;

class PluginX_TripController extends BaseController {

    protected $allowAnonymous = false;

    public function actionIndex() {

        // let's instantiate a Http client programatically
        $clientConfig = Orchestrate\default_http_config();
        $httpClient = new GuzzleClient($clientConfig);

        // instatiate the collection
        $trips = new Trips($httpClient);

        $trip = $trips->item('ING');

Any thoughts?

Problem was with how composer handles psr-0 and psr-4 autoloading, so by changing the composer.json like such, the classes were loaded.

{
  "autoload":{
    "psr-4": {"PluginX\\": "PluginX/"}
  },
  "require": {
    "andrefelipe/orchestrate-php": "0.14.0"
  }
}


{basePath} creates a folder named {basePath} issue just built a blog with craft, and I got some issues with assets pathing.
In the general.php I put

return array(
    'environmentVariables' => array(
            'basePath' => '/images',
            'baseUrl'  => 'https://site.com',
        )
);

But when I put {basePath} to assets path, the system creates a {basePath} named folder in root and looks for the image folder there. Also the {baseUrl} is looking like this in the code:

https://site.com/{baseUrl}/images/image.jpg

Am I doing something wrong?

Assuming this is using Craft 3, you should use aliases.

In your config/general.php add:

'aliases' => [
    'web' => 'https://site.com',
    'webroot' => dirname(__DIR__) . '/web'
],

Then in your Control Panel, under Settings → Assets → Images, set your Base URL to @web/images and File System Path to @webroot/images.


Mcrypt is required on OS X Mavericks 10.9.4 I'm stuck on the /admin/install page, getting an error "Can't run Craft :(" saying that Mcrypt is required.

I've tried installing with Homebrew, but kept getting an error. So, I installed mcrypt manually using these instructions on Stack Overflow. PHP and Mcrypt are installed:

$ which php
/usr/local/bin/php

$ which mcrypt
/usr/local/bin/mcrypt

And in my php.ini file I've added:

extension=mcrypt.so

(I've also tried including the path extension=/usr/local/bin/mcrypt.so)

In the ;extension area (around line 880).

Even after restarting Apache, I still get the same error that "Mcrypt isn't installed" from Craft.

Here's all you need:

http://topicdesk.com/downloads/mcrypt/mcrypt-download

Works like a charm.

Update: to use brew, you have to specify the version of PHP for it to work. For example:

brew install mysql php54-mcrypt


Recurring Scheduled Tasks in Craft Is it possible to have a task (defined in a plugin) be scheduled in Craft to run on a recurring basis without having to use cron?

If so, where do I put those settings (eg, to run a task hourly)?

Currently not... after all, the task has to be triggered by something (either a cron job or a PHP request to kick it off).

We've discussed the possibility of adding quasi-cron support natively in the future.  It wouldn't be 100% accurate, though, since it would still require a PHP request to trigger it. At most you'd be able to say something like "Start this task at 8PM tomorrow", but it wouldn't actually start until the first PHP request that occurs after 8PM tomorrow.


Let a client log in to the site when the system is off I would like to let a client log in to the site when the system is off, but without CP access. I have created a user group named «testing-group» with one checkbox checked: «Access the site when the system is off», and I have assigned a user to this group. I have created a 503.html template in the templates folder, and the login form provided in the docs,  http://buildwithcraft.com/docs/templating/login-form, is in this template. The form is displayed, but nothing happens when I try to log in (happens both with admin account and the user assigned to the group «testing-group» ).

Turns out there was a bug in Craft that prevented a scenario like the one you're trying to achieve from happening.

It has been fixed for the next (post 2.4.2702) release, though!


I want my custom field values to be stored on a per-locale basis, but can't seem to do this. Currently building a multi-lingual site. Developing locally using WAMP. Using trial version of 'Craft Pro'. Followed the step-by-step instructions of Craft's Setting Up a Localized Site

All works well except for one thing: Step 3: Define your translatable fields.

I can't make this work. When I check/tick my custom field's “This field is translatable” checkboxes, they don't seem to work as expected.

Problem

When I create an entry, put some values in the English locale, then hit save, all values get copied over to the French locale.

This means the moment I hit save, the French version of my site will display English content until I update it with the translation.

Am I doing something wrong?

I'm considering creating locale-specific sections to get around this problem.

Any help, much appreciated.

My current folder structure is as follows:

assets
craft
french
uk

No, you're not doing anything wrong. Craft copies the content over to all the other locales when you save an entry for the first time.

The idea behind this is to give content editors a base for the translation, and for some content it’s not even necessary to translate at all. Imagine a text field for city names for example, you don’t need to translate "Berlin" or "New York" for some locales, but for "Berlin and Munich" the German translation would be "Berlin und München".

One feature you might not have discovered is the "Default Entry Status" setting in the section settings. If you disable a locale by default, Craft will still copy over the content on the first save, but the entry won’t be live for this locale yet, you first have to explicitly enable the locale in the right pane of the edit entry view.


Is there a way to control the order of appearance of shipping methods in Craft Commerce? If there are multiple shipping methods available for an order, is there way to control the order in which they appear?
The CP doesn't seem to offer a way to re-order them. I'm using something like the following code to retrieve all available methods.
{% for handle, method in cart.availableShippingMethods %}
<input type="radio" id="{{ handle }}" name="shippingMethodHandle" value="{{ handle }}" />
{{ method.name }}

{% endfor %}

Craft Pro (3.4.28.1) & Craft Commerce Pro (3.1.12)

I don't think there is any in-built way to do this, no.
A relatively easy hack to achieve it, though, is to loop through your shipping methods (as youare) - but rather than directly outputting them, instead add the data to a twig array (possibly adding some extra data long the way, such as a sortOrder of your choosing, based on the handle) - and then use Twig's sort to sort your options based on your desired criteria (e.g. the aformentioned sortOrder or just by e.g. the price - before then actually outputting those options from the array, rather than the initial direct loop.
It's not awesome/elegant, but it works!


Is it possible to limit the level at which entries can be selected from within an entries field? I have an entires field which is using a structure as a source.
The structure has 3 levels and I would like to be able to limit it so the user can only select entries at the second level.

I've had a look through the docs and at the field settings but it doesn't seem to be doable. If anyone knows a work around or a plugin which can do this that would be great. I wonder if it is possible to create a plugin to extend this field to do this if not?

There's already a popular feature request for this:
"Entry Type" setting for Entries fields

But yes, it's currently also possible to do this by extending the default entries field type
and adding your custom criteria with getInputSelectionCriteria().

class BusinessLogic_CustomEntriesFieldType extends EntriesFieldType
{
    public function getName()
    {
        return Craft::t('Entries (custom)');
    }

    protected function getInputSelectionCriteria()
    {
        return array(
            'level' => 2
        );
    }
}


Image Upload "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" I'm getting my nerves on this because I can't find what's stopping from uploading. I simply choose a file, the loading show and get itself complete, but it simply stops at the 100%. I ran into my browser's console and this shows up:

Safari:
"Failed to load resource: the server responded with a status of 500 (Internal Server Error)"

Chrome:
"Failed to load resource: http://craft.dev/index.php/admin/actions/assets/uploadFile the server responded with a status of 500 (Internal Server Error)"

Please help me to figure this out... A huge thanks in advance!

I'm running the website on localhost and using AMPPS and Navicat for the DB.

UPDATE

Got an answer here. It was me the problem the whole long. I read through my error logs (thanks Brad on that!) and found out that I had that the my php's gd extension wasn't active. I activated and I now have it working!
Thanks for all the help!


Performance basics? BlogPost+Comments vs. One ever-expanding Matrix Field? New to Craft, and unsure how it works under the hood.  In terms of overall performance, I'm curious to know which of the following scenarios is the most performant approach in terms of DB queries and server strain.

SETUP: I'm building a sort of blog/forum hybrid with user-generated posts.  But in this case, comments are not an afterthought tacked onto the main post (like most blogs).  Instead, comments are a central part of the overall content.  Sort of like StackExchange or Reddit.

SCALABILITY: Let's prepare for a site that grows to a million+ Posts... and millions more Comments.

IDEA 1: Build a traditional BlogPost/Comment system where each new Post requires users to upload a single image and a rich-text description.  Then Comments are tacked on as usual.

IDEA 2: Build each BlogPost with a Matrix Row featuring only 2 fields [ image | rich-text ], and instead of tacking on traditional comments, simply append additional rows to the post's Matrix Field via front-end editor form.

While Idea 1 is well-tested and proven, I think Idea 2 might save a lot of computational power on page delivery.

If I understand correctly, Idea 1 must make at least 2 (and probably several) loops through the database, first the Blog and then the Comments...

But Idea 2 needs only one loop through the Post/Matrix to grab everything. And then even little things would become easier, (e.g. Comment count = how many rows in the Matrix.  AND Image count = how many images in the entire Matrix field.  AND most recently updated post = most recent Post/Matrix update, not most recent Comment).... all without doing additional queries on a Comments table.

QUESTION 1: Is my understanding flawed, or does Idea 2 make more sense in terms of fewer queries and server load?

QUESTION 2: With Craft, is it possible for a Matrix field to be appended row by row from a front-end form?

Regarding performance:
If you look at the database structure of Craft, you'll see that Matrix content is stored across multiple tables, with each block having its own record, just like entries do. I've never compared calculations, but I'd bet there's no significant difference in the DB performance between your two ideas. Using eager loading you could retrieve a BlogPost entry and all Comment entries related to it in three DB queries.
If you want to run a quick exercise to test your theory of performance, model out both options. Create one entry that has 10 "comment" Matrix blocks, and one entry that has 10 related "comment" entries. Don't even worry about a front end, just create two empty templates—one for each approach—that get the respective entry and its comments. Use the Yii front-end profiler (activated under your user account's Preferences tab) to check out the performance difference. This will suggest what kind of performance difference there might be.
Also keep in mind that once you layer on your page caching strategy, performance differences might be a moot point.
Regarding usability:
From a management standpoint, idea 1 sounds much easier to work with, as you're utilizing Craft's content structure in a natural way (as you said, idea 1 is a well-tested and proven approach to this use case). Craft already exposes a very streamlined API for creating, editing, deleting, and querying entries. Doing the same for a Matrix field on an entry is certainly possible, but you'll probably end up writing your own interface if you plan on doing that at scale.
Also consider the interface within Craft for you to manage things. A Comment entry type already has a dedicated admin section for you to browse, search, sort, and manage comments. Trying to do any sort of query across Matrix blocks distributed among BlogPost entries is not built in to Craft's interface; you'd have to write a whole plugin to add that functionality yourself.
I'd go with idea 1 for sure.


Craft Commerce one time billing address creation Could it be possible in Craft Commerce to let an admin create a customer with a one time set billing address and that the customer can only set shipping address in the order process?

Currently there's not much in the way of back end support for creating customers as such.  You can create craft Users in the back end, but given a commerce customer is not necessarily a Craft user, I think the short answer is no.

You could certainly create front end stuff that effectively achieves this though - how you prep all the form work for addresses is up to you, so you could e.g. force your checkout flow to go through a 'set billing address' page the first time and then simply never offers the opportunity to change that later.

You could even create forms for this part of the process that are only accessible by admin, so that you're creating your own 'back end' interface for this....and then pass off the created customers to your actual customers who then see a checkout that only lets them set the billing address.


Matrix fields using Categories Trying to template a matrix field that contains the use of categories. I am not a dev but trying to get this working.  This is my attempted but what I get back is something like this instead of the result.

  {{%content}}";s:12:"customFields";N;s:9:"inReverse";b:0;s:7:"asArray";b:0;s:2:"id";N;s:3:"uid";N;s:10:"fixedOrder";b:0;s:6:"status";a:1:{i:0;s:7:"enabled";}s:8:"archived";b:0;s:11:"dateCreated";N;s:11:"dateUpdate

Here is my code...

{% set entries = craft.entries.section('bizlist').limit(10) %}
  {% for entry in entries %}
{{ entry.title }}<br />
     {% for block in entry.cityList %}
{{ block.bizName }}
     {% endfor %}
  {% endfor %}

Is bizName your categories field?  Try something like:

{% for category in block.bizName.all() %}
   {{ category.title }}
{% endfor %}


Check to See if Field Exists When looping through a matrix, is there aquick way to check whether or not the block has a particular field (not if the field is empty, but if the field exists at all).

I have a matrix with ~20 block types, 12 or so have a field called blockTitle. For in-page nav, I'd like to loop through all the blocks and just output blockTitle for those that do have it. I could do this with a conditional for block.type, but am wondering if there's a simpler check (in case we add more block types in the future, don't want to have to update the conditional every time).

Using {% if block.blockTitle %} will kick back "Craft\MatrixBlockModel and its behaviors do not have a method or closure named "blockTitle"." for block types without that field, so that's a no go.

Tks.

This should work:

{% if block['blockTitle'] is defined %}
    // Do your thing
{% endif %}


whether to use Craft or not? I developed a web site some years ago in PHP and mySQL.  I'm wondering if it would be worthwhile to convert it to a CMS like Craft.

The site -- http://blacksmiths.mygenwebs.com -- displays information on historical figures -- "tradesmen".  These are arranged by region, so "Devon", for example, contains all people who lived in that region and performed that service.
The lady the site belongs to collects the data and puts it into a spreadsheet and uploads the comma-delimited .csv files to the site.  (no, she won't consider abandoning her spreadsheets)
The software reads the .csv files and creates a page for each .csv file
It also uses the CSV file to create the home page (at the link above)

I would like to change the operation slightly

have the uploaded .csv data placed into a database table and the pages be dynamically generated from there (there are only nine fields in each row).
have a form where she can input new data
be able to export the data to the spreadsheet format she likes

There is also an administrative back-end, all in PHP-mySQL, that stores data on contributors, which tradsman they contributed and their email address, if it is to be displayed on one of the pages (right now, the email uses javascript obfuscation, but each should really use a contact form to protect the email addresses).

it would be useful to create links between the tradesman table record and the contributor table record.

I can do all this in PHP, but I'd like to see if Craft could make this simpler.

I'm looking for suggestions as to whether going to a CMS like Craft would be a good idea and perhaps some suggestions on how to go about it.

Craft is using PHP and MySQL. What it gives you is a framework where a lot of the difficult stuff is already covered. Things like content modelling, user administration, security, etc is already done.

In addition there is a good plugin environment that can help fill in gaps to required functionality.

Of course, you can also extend it as you wish to add even more custom functionality.

For your particular use case I'd say Craft is a very good fit. You wouldn't need to be concerned with building an administration interface and the data you wish to store can be easily modelled.

Since your client wants to keep the spreadsheets then a plugin like FeedMe would be brilliant. You can set up an import in FeedMe and have it pull in the data from the spreadsheet using a cronjob or when your client wants to run an update. She'd just need to click a button. The data from the spreadsheet would be imported and used to create new, or update existing, content entries.

You might find that given Craft's really nice control panel she would also find that it's easier to enter data directly than follow the spreadsheet->import process.

So yes. Craft would be a very good fit.

Edited in light of your comment/question

You don't need to create your own database tables or write your own queries. That is what Craft is doing for you.

Craft is extremely flexible in that it will allow you to model your content pretty much however you wish. This data model is then stored within Craft's own database schema and content is written/read (by Craft) using the Yii/Yii2 PHP framework. You would then use the templating language (Twig) to create a front-end for the website with no need to use PHP at all.

So, let's say you had a Section of entries for Blacksmiths. Each Blacksmith is an entry, with whatever fields you wish stored within them.

Let's assume you want to list out all of the Blacksmith's stored in the Blacksmiths section to create an index.

You might do that within your template with Twig like so:

{% set blacksmiths = craft.entries.section('blacksmiths').orderBy('title').all() %}

This would give you an iterable object named 'blacksmiths' that you could loop over to output the content you want (taking a rough version of your actual listing page).

    {% for blacksmith in blacksmiths %}

        {{ blacksmith.surname }}
        {{ blacksmith.firstname }}
        {{ blacksmith.trade }}
        {{ blacksmith.year }}
        {{ blacksmith.notes }}

    {% endfor %}

If you wanted to alter precisely which blacksmith entries to retrieve you would include some additional criteria in your initial query. You don't need to worry about joins because the data has been stored within Craft's schema and Craft handles any criteria or relations that are required.


Craft Commerce - Handling Product Types I am using Craft Commerce for the first time and am trying to dynamically generate a dropdown menu that contains links to each product type. I thought the best way to accomplish this would be by using a parameter in the URL i.e.

myurl.com/commerce/products?cat=books

I would be able to get the handle of the selected product type by using:

craft.commerce.products.type(productType).find()

I have two roadblocks that are preventing me from implementing this:

How do I get an array of all the product types so I can build the dropdown?
How do I get the name of a product type once I have the handle so I can display a Header at the top of the page based on the selected product type?

Also, is there a better way of implementing similar functionality that I am simply overlooking?

Thanks!

You can get all product types within your templates with:

{% for productType in craft.commerce.productTypes %}
  {{ productType.name }}<br>
{% endfor %}

There is no way to get a specific product type within templates at the moment, but I have added to the list. In the meantime you would need to look over all and find the one you want as above.


Filter Entries by Custom date I want to output all entries which match with a given year from a custom date field. The year is a string I get from slug. I am using Craft 3.5.16. What did I do wrong?
{% set catYear = craft.app.request.segment(-1) %}

{% set firstDayOfYear = now | date_modify('1 January ' ~ catYear) %}
{% set lastDayOfYear = now | date_modify('31 December ' ~ catYear) %}

{% set params = {
  section : 'termine',
  datumTermin : 'and, >= ' ~ firstDayOfYear|date ~ ', <= ' ~ lastDayOfYear|date
} %}

{% set beitrage = craft.entries(params).all %}

You need to query using strings and your condition should be written as follow:
{% set catYear = craft.app.request.segment(-1) %}

{% set firstDayOfYear = catYear ~ "-01-01" %}
{% set lastDayOfYear = catYear ~ "-12-31" %}

{% set params = {
    section : 'termine',
    datumTermin : ['and', '>=' ~ firstDayOfYear, '<= ' ~ lastDayOfYear]
} %}

{% set beitrage = craft.entries(params).all %}

See documentation for reference :)


Build a language switcher for a one page website? I'm building a site with two languages, and I need a language switcher so wherever you enter the website you can switch the language easily. The website is a onepager, so i can't direct to a specific language URL. Instead i'm thinking of adding a segment (/de /fr) to the URL.

I don't know how to display the language fields and language globals.

The basics for setting up your localized site are nicely written down in the Localization Guide. This walks you through the steps necessary to make your site being available under their subfolders /de and /fr.

Set up correctly, your templates will always show the field content translated to the currently accessed locale.

If your one-pager template is not connected to an entry (case 4 in the Routing article) and you simply save your template files at templates/de/index.html and templates/fr/index.html (case 6), have a look at the include tag, that allows you to maintain one template responsible for all of your locales (e.g. {% include '../de/index.html' %}).

The following code is a simplified version of the example I wrote down here, and should do fine for a one-page website:

{# Loop through selected site locales #}
{% set locales = ['de', 'fr'] %}
{% for locale in locales %}

    {# Check if `locale` equals the requested page locale #}
    {% if locale == craft.locale %}
        {% set current = true %}
    {% endif %}

    {# Output a link to the hompage and add a class "current" to the current locale's link #}
    {{ craft.i18n.getLocaleById(locale).name }}

{% endfor %}


Deleting Stale Template Caches Failed I continue to see these pile up. If I clear my template cache, I can hit retry on each and they go away, but that's getting tedious.

I have the following from a P&T support request on these a while back, but is there any way to track down where/why these are happening now? I'm not seeing any deprecated tag errors or anything in the CP, nor am I seeing any template errors on the site, and I have a fair number of pages cached where images are being resized.

Hrm... I see the error that's occurring in your log files when that task tries to complete. What looks like happened was that there was an error in your Twig code somewhere inside of one of your {% cache %} tags and that error actually got cached and saved to the database and that is freaking the DeleteStaleTemplatesCache task out.
Kinda hard to back track which cache tag it occurred in and what part of your template code.
But the way to get it worked again is to clear your template caches manually from Settings->Tools. You should be able to click "retry" on those failed tasks again and they should complete fine.

Thanks!
Mark

When a task actually fails (as opposed to getting stuck), Craft will log an error message explaining why. To fish it up, open craft/storage/runtime/logs/craft.log, and search for:

Encountered an error running task

Each time the task runner encounters an error, its log message will begin with that, followed by the task’s ID, its type, which step it was on (if applicable), and the error message the actual task returned.

If you’re not seeing it, check craft.log.1, craft.log.2, etc.


Craft 3 forgets plugins Due to problems I had with Craft 3 Beta 23 I switched back to version Beta 22 (I did this a couple of times)

I do this by importing an sql dump of beta 22 and by directly requesting Beta 22 via composer.

The strange thing: Craft forgets about Plugins it had installed. They simply do not appear anymore in the plugins list, although they are installed via composer and nothing changed in them.

I cleared storage/runtime and I also cleared the DB cache via utilities, that does not help.

Any hints why Craft does not show the plugins anymore in the list? Is there another cache?

Craft 3 knows about available plugins via the vendor/craftcms/plugins.php file, which stores info about all Composer packages that were installed with type: craft-plugin in composer.json.

If that file doesn’t exist or is just returning an empty array, then make sure that the craftcms/plugin-installer Composer package is installed, and try re-requiring each of your Craft plugins. As they are (re-)installed, they should get added to plugins.php.


Limit amount of entries a user can create based on their user group Is there a way to enforce a limit to the amount of entries a user can create based on their user group

I’ve been digging around a little and can’t seem to find anything that would allow this, I’ve looked at adding my own permissions but I don’t think that’s right as I need/want the value to be a number, not a ‘can the user add x amount’ kinda deal.

Something like:

{% set entries = craft.entries.section(‘listing’).authorId(user.id) %}

{% if entries.count >= userGroup.entryLimit %}
    No more entries for you!
{% else %}
    More entries for you!
{% endif %}

Is the only way to do this by creating a custom plugin?

Thank you!

I think a custom plugin is going to be the way to go with this.  Your template code would look something like:

{% set entries = craft.entries.section(‘listing’).authorId(user.id) %}

{% if entries.count >= craft.myPlugin.getEntryLimitForUser(user.id) %}
    No more entries for you!
{% else %}
    More entries for you!
{% endif %}

Your plugin would also hook onto the onSaveEntry event and keep an incrementing entry save counter for each user you're tracking.


multi language - each in its own folder? Craft looks VERY promising to me! Still try to figure out if it could be perfect for our new project, though.

Our website will be in English and German (accessible under ONE domain - see below). I understand that there is a plugin with which I can switch the language while staying on the very same page - PERFEKT!

Here's my questions. Can those requirements be fulfilled by Craft?

We want the English content to be placed in the folder "website.com/en" and the German in "website.com/de". We would manually put an index.php with a redirect to our default language (not decided yet) in the root folder.
Can we completely build up the site in one language first - and then kinda "import/duplicate" it to the second language and translate it? language-switch links should still work afterwards. Means: Craft should know which articles of each language belong together.
There is no 'tab' above an WYSIWYG field under the very same article where I can switch between languages and fill in the corresponding content on the very same admin-page, right?

I'll open another question for my questions concerning my other topics...

Thanks for your help and greetings!

"there is no 'tab' above an wysiwyg field under the very same article where i can switch between languages and fill in the corresponding content on the very same admin-page, right?"

Actually, there is (sort of). It's not a tab per se, but you can switch between the different versions of each entry as you are editing them.

So you would add all of your entries in English first, then circle back and adjust the content for each entry in German.

And as you mentioned, there is a Site Switcher plugin (disclaimer, I am the author) to let you easily switch between languages while staying on the same page.


Allow users to edit user account email from front end form in Craft 3? Is there a way to allow users to edit their email address via a front-end form in Craft 3?

My understanding is this would require an 'elevated' user session. Which I'm guessing can only be achieved via plugin. In the API docs I see that there is a startElevatedSession() method.

At a minimum, I'm assuming this might work:

Submit form with existing password and new email to a custom controller.
Controller starts an elevated session via startElevatedSession(), sets new password on user, saves user, and redirects to success page.

If I were to create a 'confirm email' workflow for security — how might that work? Can I tap into the Craft native workflow? Or would it all need to be custom?

FYI... in this case, the site is set to useEmailAsUsername if that makes a difference.

As a follow-up, would changing the email address affect relationships to commerce orders? I assume that they are related by something other than just email address.

Any general pointers would be much appreciated. Thanks.

UsersController::actionStartElevatedSession() is public so you can access it via frontend form but you should only call it via ajax request.

You can just submit your normal user form via ajax and if it contains an error with key currentPassword you can be sure to require a elevated session and display a password form to enter it in order to create a request to the route above. This will start the session and you can submit the user form a second time.

So in summary: you don't need a custom controller at all. You can change the user's email and password by submitting a form with newPassword and email but you'll receive the error Incorrect current password if there is no elevated session or if the password parameter doesn't match the user's old password (you always need to submit it together).

If you want additional security you can send the sendVerificationEmail to force users to verify their email by sending them a mail. But keep in mind all those things can be manipulated via frontend request. Users are totally free to change the html of your form


Element API: Remove additional set of square brackets from JSON-String We're currently having an Android-App access some of the entries of our Craft-based website. We are currently still using a self built API, and for easier creation of new API-Calls we are trying to migrate over to Pixel & Tonic's Element API plugin.

The entries (or the blocks of a Matrix-field of that entry, to be more precise) are accessed like so:

'api/alloverlist' => function() { // GET ALLOVER-CHALLENGES
        return [
            'elementType' => ElementType::Entry,
            'criteria' => [
                'section' => 'challenges',
                ],
            'paginate' => false,
            'first' => true,
            'transformer' => function(EntryModel $entry){

                $allOverChallenges = [];
                foreach ($entry->allOverChallenge as $challenge){
                    $allOverChallenges[] = [
                        'elementId' => $challenge->id,
                        'field_allOverChallenge_allOverName' => $challenge->allOverName,
                    ];
                }

                return [
                    $allOverChallenges
                ];
            },
        ];
    },

The returned JSON-String has the following appearance:

[
[
    {
        "elementId": "1298",
        "field_allOverChallenge_allOverName": "Dein schönster Sonnenaufgang"
    },
    {
        "elementId": "1310",
        "field_allOverChallenge_allOverName": "AllOverChallenge2"
    },
    {
        "elementId": "1318",
        "field_allOverChallenge_allOverName": "Allover Challenge 3"
    }
]
]

However, the Android-App accepts the JSON-String just with single square-brackets, like so:

[
   {
     "key":"value",
      ...
   },

   {
     "key":"value",
      ...
   }
]

For the sake of not having to change the existing Android-App, is it somehow possible to remove the additional square brackets?

Thanks.

Though I don't know the Element API, have you tried

    return $allOverChallenges;

instead of

    return [
        $allOverChallenges
    ];

It looks like you are simply adding these brackets (Array) on the return.


404 Error on Image Transforms Transformed Images are failing to load with a 404 error  For example:

http://mysite.com/index.php?p=cpresources/transforms/382&x=v0nGRK3Qr

This happened after I swapped the db.  So, everything had previously been working.

Also:

My images reside /public_html/mysite/img/posts/
BUT, Update Asset Indexes generates The path of your source "Main Post Image" appears to be invalid And, none of the images load when I try to view Assets in cp.
I can access the image from the public URL to the assets is http://www.mysite.com/img/posts.  And, I can access the original uploaded images here.
I assume the path to my images (which I understand can be different from the URL) is the problem.
Path is current set to /mysite/img/posts/'.  I have tried multiple permutations - nothing seems to work.

Help/Thanks

/mysite/img/posts/ is an absolute path pointing to the root of your drive mount.

You probably just need to make it relative.  i.e. either mysite/img/posts or ./mysite/img/posts.


image transforms issue with CMYK images The builtin craft image resizer tool appears to be having issues with CMYK source images, we're using Craft 2.5 (latest version)

Original source image

http://2b45fe03c2dbd491035c-f318885d2d6632cd7d9eb38c0fa500f2.r62.cf1.rackcdn.com/new_site/film/images/EXM_D016_02432_42886.jpg

Transforms to this

http://2b45fe03c2dbd491035c-f318885d2d6632cd7d9eb38c0fa500f2.r62.cf1.rackcdn.com/new_site/film/images/_assetImageGrid/EXM_D016_02432_42886.jpg

Is there a solution to this issue that we can implement, or is it simply a case that CMYK images cannot be resized by the system?

Thanks

Craft Developer has responded and confirmed that there was an issue and offered a fix, this issue will be resolved in the next release of Craft.  Version 2.5.2767 contains the issue, so any version higher than this will contain the fix.


Dump SQL query in Twig template Is possible to dump a query made on a twig template for a statement like this one for example:

craft.entries.section('homepage')

Can we some how see the actual SQL query ?

In Craft 3 you can use getRawSql() at the end of the element query.

{% set entries = craft.entries.section('blog').getRawSql() %}

{{ entries }}


Issues loading files from within css files i just started using craft on a local domain and i have some issues.
my stylesheet(a few files) are loaded using html<link rel="stylesheet" href="style/style.css">, and it works great for css and js files, but files requested from within the css aren't loading.
for example the Font Awesome @fontface.

Any ideas? and the is any issue using html instead of the {{ getHeadHtml() }} method?

Thanks Ahead!

For static assets I usually use something like this:

{% if craft.debugMode %}
    {% set assetsUrl = siteUrl %}
{% else %}
    {% set assetsUrl = "assets.mysite.com" %}
{% endif %}

And then I can set assets URL's the same way as navigation URLs. ie.

{% includeJsFile assetsUrl ~ "js/init.js" %}

{% includecss %}
body.landing #page-wrapper {
    background-image: url(" {{ assetsUrl }}img/pic01.jpg  }}");

}
{% endincludecss %}


Do dynamic routes depend on url rewriting? I need to set up a custom route for a particular page, but can't seem to get anything to work.

For instance, I set up this route:

From what I gather, this should match just about anything... mysite.dev/hello, or mysite.dev/goodbye. But no matter what I try, I get tossed back to my index.

My only theory right now is that the Craft url structure is strange. I navigate around just fine, but there is no rewrite happening. So instead of http://mysite.dev/site-sections/we-work-on, it's http://mysite.dev/index.php?p=site-sections/we-work-on. I think this is because I'm developing on a Homestead box, which uses nginx and not apache.

Do dynamic routes depend on url rewriting?

I first attempted, with the link Mats posted, to edit my nginx config. That resulted in a rather terrifying "can't even find the index" error, but there was a silver lining: after destroying and recreating my Vagrant the urls mysteriously fixed themselves, and I no longer see querystrings on the index. Custom routes also now work. So that's mysterious but I'll take it for now.


Pulling Data Across Entry Types On our play pages (ex. http://actors-express.com.s102768.gridserver.com/plays/liaisons), we list our each of the cast members, their headshot and role. We did this by creating a matrix field that pulls in the Entry for each person and relates it to the specifics for the show.

We would like to write code on the template for their bio page (ex. http://actors-express.com.s102768.gridserver.com/people/kristin-butler) that will scan through all those matrices on play pages and find out which plays they have been in, then display a list of plays with links to each of their URLs. It would be nice to pull in what their role was in the play, but that's not a requirement at this point.

We would also perform a lookup and see if one of the plays was currently on stage (a flag on our play entry type), or if it was upcoming to pull it into the module above on the right.

To access related entries stored in a matrix field, you need to specify the targetElement (actor/entry) and the matrix field (using dot syntax 'matrixFieldHandle.entriesFieldHandle') from 'plays'.

In your actor biography template:

Actor: {{ entry.title }}

{% set plays = craft.entries.section('plays').relatedTo({
    targetElement: entry,
    field: 'actorsMatrixFieldHandle.actor'
}) %}

Plays:

    {% for play in plays %}

            {{ play.title }}

            {% if play.onStage %}
                ON STAGE
            {% endif %}

    {% endfor %}

To get the role is little more difficult — you first need to find the actor's matrix block in the related 'play' record. We can do this by testing each block to see if it matches the current entry (actor), or use an if clause in the loop.

    {% for play in plays %}

        {% set role = '' %}
        {% for block in play.actorsMatrixFieldHandle if block.actor.first.title == entry.title %}
            {% set role = block.role %}
        {% endfor %}

            {{ play.title }}

            {{ role }}

            {% if play.onStage %}
                ON STAGE
            {% endif %}

    {% endfor %}

You could also try to set the title field as a parameter to the Matrix block query:

{% set actorBlocks = play.actorsMatrixFieldHandle.title(entry.title) %}
{% set role = actorBlocks|length ? actorBlocks.first().role : '' %}


Showing pagination for a date range of entries Pulling hair out here so looking for divine inspiration.

Trying to list a set of events/entries grouped by day. This is fine when all the dates are organised by an event date but when we introduce a date span (event start date and event end date) am struggling to work out how to get days that are not specifically occurring on a set day to appear, eg if starts Tuesday and ends Thursday to show on Wednesday.

I can get this working with an arbitrary range, eg to show all the events across a certain month but this gets considerably more complicated introducing pagination when no date range is specified. Ideally need to paginate by dates but pagination requires the ElementCriteriaModel.

Any thoughts on how might go about this as banging head against a brick wall …

It's difficult to give specific code help without seeing some input/output examples, but here's a go-by:

You can say that an event occurs during a date range if:

The event begins before the date range ends
and, the event ends after the date range begins

So, the pseudocode looks something like:

Prepare a DateTime representation of the range rangeStartTime (e.g. today at 00:00)
Prepare a DateTime representation of the range rangeEndTime (e.g. tomorrow at 00:00)
For each event, check if the criteria are satisfied: eventStartTime < dayEndTime and eventEndTime > dayStartTime
If the criteria is satisfied, include the event.

So, let's say each of my Event entries has eventStartDate and eventEndDate fields, and I want to list out all the events that occur today (i.e. including, for example, events that started yesterday and end tomorrow).

I could do something like...

{% set dateRangeStart = today|date('Y-m-d') %}

{% set dateRangeEnd = tomorrow|date('Y-m-d') %}

{% set eventsInRange = craft.entries
    .section('events')
    .eventStartDate('<'~dateRangeEnd)
    .eventEndDate('>'~dateRangeStart)
%}

Now eventsInRange is an ElementCriteriaModel that finds all Event entries in our date range. And since it's an ElementCriteriaModel, you can plug it into the {% paginate %} tag to get paginated results according to whatever other parameters you desire.


How to redirect the page In the front-end, I create a form and submit the data to backend. In the controller, if got some errors, I would like to redirect to the previous page with some information.

If you're using the Pixel & Tonic Contact Form plugin then there is a way to set your redirect using {{ redirectInput('contact/thanks') }} as seen here: https://github.com/craftcms/contact-form

However, I've just noticed you've tagged this question with plugin-sproutseo, but I'm not aware of that plugin interacting with contact forms in any way.

To more specifically try to answer your question, firstly to redirect and pass some information, I have used query params before so I've set my redirect link to be /thankyou?name={{ formstuff.name }} so I can access the user's name with:

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

Now when it comes to redirecting back to the user's previous page, have a read of this answer below. It's a few years old, but it'd potentially still give you an option to resolve your issue: https://craftcms.stackexchange.com/a/13488/5845

EDIT: After a look at some other questions, I've noticed this one has an almost identical wording so this one should be marked as duplicate. See dupe below:

How to redirect the page with params?


How do you raise/fake an event so that you can test handlers listening for it? We use event integration (native and custom) in a lot of the plugins we build and I was wondering if anyone has come up with a simple way to raise those events at will, without having to follow a specific flow of execution.

For example, if you are listening for entries.saveEntry and don't want to manually save an entry in order for that event to be raised/triggered.

I think it would be nice to have a simple way of doing this and interested in seeing if anyone has found the need for such thing.

With enough patience, one could fake many events and call the service that raises them but I'm sure that there other developer way more clever than me that may have solved this already.

I believe events can be raised programmatically by calling them from services. You could mimic this behavior by creating an Event object ($event) and calling calling craft()->entries->onBeforeSaveEntry($event) yourself, for example. You would need to set up the event context and create a new Event object as the code does in the Entries Service below.

$event = new Event($this, array(
  'entry'      => $entry,
  'isNewEntry' => $isNewEntry
));

$this->onBeforeSaveEntry($event);

Check out the Entries Service around lines 165 to see how Craft uses events in that context.

For each event call, the code is calling $this->raiseEvent('eventName', $event);

I bet with some minimal setup, you could write a test controller that can call these events at will. Good question - I've been going down the manual path for all my testing too!


Can someone help me identify why my entry is invalidating? I have a custom plugin that's saving an entry successfully. While saving the entry I'm setting our "merchant" field (an entries field, limit=1) like so:

<?php
# ...
$entry = newEntryModel();
# set the sectionId, typeId, authorId, and some other fields...
$entry->getContent()->merchant = (isset($data['merchant']) ? [$data['merchant']->id] : null; // $data['merchant'] is an EntryModel

This appears to be fine in the CP. I can see and edit the related entry.

However later in the application I have to update this entry and when updating the entry, I'm only updating a single field. While debugging the EntryModel that I'm trying to save I see that if I var_dump $entry->merchant I get an ElementCriteriaModel yet when I dump $entry->getContent->merchant I get 'null'.

My log shows the following error:

  2014/10/31 18:25:46 [warning] [application]
  Craft\ContentModel->merchant failed validation: Merchant cannot be
  blank.

According to this tweet it seems like dumping $entry->getContent()->merchant should be returning a ContentModel instead of null.

Any ideas?

EDIT: I've confirmed that everything works as expected if the field is NOT marked as required. However, this can't really be a solution - I need to make sure that the client cannot leave this field blank.

getContent() will return the element’s ContentModel, NOT getContent()->merchant, which is just an attribute of the ContentModel—sorry for the confusion.

I’ve just posted a separate Q&A fully explaining what the ContentModel is used for here:

What is getContent() / the ContentModel, and how do I use it to get and set custom field values?

What you are experiencing is actually a slight bug in Craft’s validation logic. Relational fields have a feature where their data is not actually required to be in POST when saving an entry. If that’s the case (if their value in the ContentModel ends up just being null), then they will simply not make any changes to the element’s relationships - the field value will be left untouched.

However the ContentModel is not aware of that feature, and it’s the ContentModel that is currently in charge of enforcing Required Field validation. So, when it gets to your relational field, and finds that its value is null, it gives you a validation error rather than letting it slide.

So, you have two workaround options, if you want to keep the data the same, but need the field to be required:

You can actually set the value based on the current value:

$entry->setContentFromPost(array(
    // ...
    'merchant' => $entry->merchant->ids(),
));

craft()->entries->saveEntry($entry);

If all you’re doing is changing custom field values (nothing entry-specific) and you’re comfortable skipping custom field validation altogether, you can just call ContentService::saveContent() directly, and pass in false to its second argument which tells it to skip validation:

$entry->setContentFromPost(array(
    // ...
    'merchant' => null, // Tells the relational field to keep the old value
));

craft()->content->saveContent($entry, false);


Entries Field Type Validation I am having some issues understanding why validation is not working on my entry forms.

I've got an entry with several field types which aren't of type "entries" and the required validation is working properly on my front end forms using craft's error macro

{% macro errorList(errors) %}
    {% if errors %}
        {% for error in errors %}
        {% endfor %}
    {% endif %}
{% endmacro %}

The validation is NOT working on my fields which are of type "entries". Do you have to pass in the error object differently to the macro since "entries" are an array?

I have tried calling the error macro like this...

{% if entry is defined %}
    {{ formErrors.errorList(entry.getErrors('houseCollege[0]')) }}
{% endif %}

and this...

{% if entry is defined %}
    {{ formErrors.errorList(entry.getErrors('houseCollege[]')) }}
{% endif %}

and this...

{% if entry is defined %}
    {{ formErrors.errorList(entry.getErrors('houseCollege')) }}
{% endif %}

and yes, I have this field marked as required in the CP.

Also I don't know how relevant this is, but in the form this value is being filled by a select element.

Relational field validation (entries, assets, tags, users, etc.) works the same on the front-end as any other custom field would.

So if you have an Entries field with a handle houseCollege on an entry and it's marked as required and there is nothing submitted on the front-end for it, then using the error macro you mentioned:

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

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

You would display any validation errors for that houseCollege field with:

{% if entry is defined %}
    {{ errorList(entry.getErrors('houseCollege')) }}
{% endif %}

And in the case of a missing required field, you'd get:

House College cannot be blank.


Scaling channels with 35 locales Not so much a technical question as a how-to/best practice one, here goes:

I'm building out a site that has 3 content-types (channels), a structure and a bunch of singles.

The site has 35 locales.

The pages & singles consist of normal translated content.

But the channels should be separate in each locale. Meaning, for example, that news items from en_UK should not be translatable to jp_JA. Content will be managed by a different user/group per locale and they should only see content published in their locale, not translatable entries from others.

The "best" solution we've come up with so far is to create a channel per locale. But that adds up quickly (3 x 35...), not to mention managing fields and permissions for each channel separately.

Is there a way to simplify this or are we going to have to bite the bullet?

Craft 3 and multisite sounds like a dream for this but sadly we can't wait for that

You could have a single News section that is enabled for each of the locales, and choose which locale each entry should target from their Edit pages.

To make it easer on the authors, you can set the default status to Disabled for each of the locales, from the section’s settings. Then when creating a new entry, the authors only have to enable the one locale that they actually want the entry to be published for.

Update

As of Craft 2.6.2972, you can configure the Entries index to only show entries that are enabled for the selected locale by installing the CP JS plugin, and pasting this code into its “Additional JavaScript” setting:

Craft.defaultIndexCriteria.localeEnabled = true;

You also may want to add this bit, to ensure that entries’ locale statuses are switched on by default from the Edit Entry page, so they don’t get lost in the entry index, which is now configured to only show locale-enabled entries:

$(document).ready(function() {
    var ls = $('#locales .lightswitch').data('lightswitch');
    if (ls) {
        ls.turnOn();
    }
});


Craft install locally with MAMP Pro Sorry to repeat this question but not yet found a fix:

Followed the install and when I try and navigate to:
site/admin

I get: "The requested URL /admin was not found on this server"
Have tried moving files around/permissions as 777, and changing the $craftpath but no joy as yet.
I use MAMP set up for other projects so is there an approach without changing MAMP settings?
Or am I missing something obvious?

Appreciate any help albeit a very basic question as want to get started!

Cheers

When I'm trying to get past my initial errors, here are some of the things I try. This is assuming you have the usual directory setup, with the webroot public on the same level as craft

Create foo.html in public, and visit yourdomain.com/foo.html. Good for mamp problems, virtual host problems, permissions problems.
edit public\index.php and add die('made it to index'); right at the top (after the <php?). Visit yourdomain.com. Good for some .htaccess problems.
edit public\index.php and add die('index is about to require '.$path); right above the require at the bottom (and of course take out the earlier die). Make sure the craft path is right.
edit craft/app/index.php and add die('made it to craft/app/index'); right at the top. Can expose some php problems (open_basedir e.g.)

That's usually enough to get me started.


Is there any way of specifying a default category for a category field? I've set up a channel using categories to distinguish between different blog post types. The majority will probably be in one category, so it would be great to be able to specify a default category. However, as far as I can see the Category field type (unlike, say, the Drop Down field type) doesn't give you the option to set a default... Is there any way of doing this?

You could output the categories in a way that makes them look like they are from a specific category when they don't have any categories assigned to them.

When you're outputting any of the entries, just add a custom link if there isn't a category assigned:

{% if entry.categories|length %}
    {% for category in entry.categories %}
        {{ category.title }}
    {% endfor %}
{% else %}
    Default Category Title
{% endif %}

Create a route that points "/blog/category/default-category-slug" to your filtered listing template (/blog/index, /blog/category etc.).

On the filtered listing template check if the default category slug is in the URL:

{% if craft.request.getSegment(3) == 'default-category-slug' %}

If that evaluates to true, you can now get the entries without any categories assigned to them and loop through them, see this question: How to find entries with no category:

{% set uncategorized = craft.entries.section('blog').search('-categories:*') %}
{% for entry in uncategorized %}
    {# show entry #}
{% endfor %}

Any other times you need to get the entries that "have" the default category, to loop through them, use .relatedTo on etc., instead of using:

{% set entriesWithDefaultCategory = craft.entries.section('blog').relatedTo('the-default-category') %}

Use this like on the filtered listing above:

{% set uncategorized = craft.entries.section('blog').search('-categories:*') %}


How to change the day of the week? Good day!

I display the day of the week on the site {{ now|date("l") }}

How to change for example Monday to Mondays (on Mondays)?

Thanks in advance :)

It looks like you're asking how to add a letter 's' to the day.
So how about using

{{ now|date("l") }}s


Accessing Commerce product variant dimensions in the template I have been unable to locate anything in the docs or any questions on here regarding how to print the dimensions associated with a variant in the template.

All I have managed to find is how to print the dimension unit using the following:

{% set dimensionUnits = craft.commerce.settings.dimensionUnits %}

Dimensions are set and accessed individually:

{% set variant = product.defaultVariant %}

{{ variant.width }}
{{ variant.height }}
{{ variant.length }}
{{ variant.weight }}


Email template issue I'm using Rias500/craft-contact-form-extensions plugin for creating custom email confirmation templates, and it works great but when I try to override the template (because I need confirmation emails per form) in my form with (which is the example in the documentation):

<input type="hidden" name="message[template]" value="{{ 'contact'|hash }}">

It will still send the email in the template I set in my CP. Am I doing something wrong?

If anyone knows another good solution for this then I like to hear it.

You can try to use craft plugin design by pixel & tonic as they are the best support with Craft CMS 2 and 3.


How do I get to the web UI in CraftCMS to install it? I initially tried this with Ubuntu Linux and a .tar.gz file without the composer tool.  I was using MySQL and PHP 7.4.  My problem is about the same with my second attempt.  I will now describe my second attempt and ask for help with it (instead of my first attempt).
I am trying to install CraftCMS on Debian 10 with composer.  Everything seems to work on the back-end.  I am using PostgreSQL and PHP 7.3.
I finally went to the web front-end portion of the directions.  In a web browser I go to /index.php?p=admin/install
It resolves to /dashboard.  The web page that is rendered says "Not Found   The Requested URL was not found on this server"
When I just go to "" in the web browser, I see "Welcome  Thanks for installing Craft CMS!"  I can click on the "Control Panel", but that takes me to a page that is Not Found.
I expect to see the screen to install CraftCMS in a web browser when I go to /index.php?p=admin/install
What am I doing wrong?

How exactly are you running Craft?
Ubuntu/Debian are just Linux operating systems, they don't necessarily come with a web server stack installed but it looks like what you're running is at least partially working.

If you getting the welcome screen, it sounds like Craft got installed so I wouldn't try reinstalling unless you can confirm there's no tables for Craft in your database.

If you can get to http://examplesite.com/index.php?p=admin/dashboard, that typically means the web server's rewrites aren't working and what you have now is a webserver configuration issue—not uncommon.

To solve a web server issue:

Apache: make sure .htaccess is located inside Craft's web folder and AllowOveride All is in your virtual host config.
Nginx: you need some special rewrite rules to get it going.
You may also need to set omitScriptNameInUrls to true in config/general.php.

If you can't get to the dashboard or the login screen, something else happened, perhaps a botched install and you should revisit how your web server got installed.


Craft CMS 3 Date Field problem I added some date fields on my entry. I select a date and save the entry.
But the date field saved the day before.

Every editing the entry continue saving the day before. When the date comes to the 27 October it stops.

İf I select before 27 Oct it's not a problem.

This video for the problem:
https://www.loom.com/share/82cb26be003540a9ae95e1f567ca0b18

I have fixed that problem. I have changed timezone settings on the Control Panel. Actually I have to use europe/ist but this timezone give that problem. So I changed to europe/kirov and my problem was fixed.