texts:
I get "Service Unavailable" when I go to my (hosted, not local) test site.

It had been working just fine until I decided to swap databases today.

I deleted the old database and replaced it with the new database.  I kept the database name the same.  I changed the username and password in cPanel and then duplicated those changes in my craft/db.php file... But no dice...  I get the nice little warning:

  Service Unavailable

  Our site is temporarily unavailable.  Please try again later.

I have checked more than once, the path, db name, username and password all check out.  Any suggestions?  ...other than start over


texts:
I am using SEOmatic on Craft 2 and want to give the user the ability to customize the Title field of Facebook's OpenGraph Title. For example, instead of showing just the Title, add a "How To" before the title is displayed.

vs.

Is there a way to do this without using a custom field and have the "How To" only display only on when the article is shared on Facebook?


texts: Is is possible to enable certain plugins only in devMode? (or via some other configuration option)?


texts:
I have a list of events which should list each event until midnight of said day.

So If a gig happens at 17:00 it should still be visible until midnight of the same day.

I came relatively close (I guess) but it's not working:

{% set nocturne = now|date_modify('today 00:00') %}
{% set midnight = nocturne|date('Y-m-d H:i') %}

This should set {{ midnight }} to midnight of the current day.

Then I translate the custom date field of each gig into the same format as {{ mdinight }}

{% set getFirstGig = craft.entries.section('gigEntry').first() %}
{% set gigDate = getFirstGig.konzertDatum|date('Y-m-d H:i') %}

Then I want to call the whole thing:

 {% set upcoming = craft.entries.section('gigEntry').gigDate('>= ' ~midnight) %}
 {% for entry in upcoming %}
   <h2>{{ entry.title }}</h2>
 {% endfor %}

The code actualy works but my test entry with the time 17:00 is not displayed here. What am I missing? And is there a neater way of writing things?


texts: How to get one entry's related stuff in Vuejs component

texts:
For example, in a vuejs component, i send a ajax request to get an article. And in this article, there is a relation field called relatedTopics.

How can I get this article's relatedTopics with something like article.relatedTopics?


texts:
Just starting to play with Craft going to be a learning curve coming from wp and processwire etc.

I created a custom Global Set and called it Logo which I assumed I could use in the _layout.html template to show a logo in the header and make it easy to change etc.

I called the set Logo and it has a handle of logo. This created the Globals option in the top nav. Here I was able to upload a logo from my assets etc.

Now in the _layout.html template I am trying to access this image by using the following but nothing shows up.

Based on the docs it says:
You can access your Global Sets from any template via their handles. For example, if you have a Global Set with the handle “companyInfo”, and it has a field with the handle “yearEstablished”, you can access that field anywhere using this code:

{{ companyInfo.yearEstablished }}

I also tried

What am I doing wrong am I going about this the wrong way?


texts:
I'd like to add very basic metadata to assets (Alttext, Caption..)

I noticed in volumes you can add custom field types – but they're not appearing when editing the entry. I found it can be edited in the assets view, but that's too complicated for editors.

If those values should be editable in the entry – should the matrix field type be used?


texts: How to remove hidden HTML from Radactor editor in CrafCMS 3

texts: I am using Redactor 1.0.1 plugin in Craft 3, When copy/paste from any website into WYSISWG boxes, hidden HTML is included. How do I remove that?


texts: I am building a custom element type and want to have the ability to archive entries. I can create a custom status for 'archived' but I've noticed base elements already have an 'archived' status I could use. Is it wise to do this? I don't know if Craft will delete elements marked as 'archived' after a period?


texts: Returning entries that contain both categories

texts:
I'm creating a filter and would like to return entries that must contain multiple categories (and behavior, not or). A sample url would be /events?cat=2,3.

{% set eventCat = craft.request.getParam('cat') %}
{% set events = craft.entries.relatedTo(eventCat).all() %}

Gives me "or" behavior and

{% set eventCat = craft.request.getParam('cat') %}
{% set events = craft.entries.relatedTo('and', eventCat).all() %}

Doesn't give me any results.

(updated to reflect Craft 3 syntax, thanks Robin!)


texts: Getting `modifyUserSortableAttributes` to work during plugin development

texts:
I have a plugin that is creating a custom field. I am using the modifyUserSortableAttributes method to make my field appear in the columns available for the Users Table and wanted to be able to sort and filter by this column. The field values is stored as a simple alphanumeric string.

More on hook/method at https://craftcms.com/docs/plugins/hooks-reference#modifyUserSortableAttributes

Call in plugin code is:

public function defineAdditionalUserTableAttributes()
{
    return array(
        'institution' => "Institution"
    );
}

public function modifyUserSortableAttributes(&$attributes)
{
    $attributes['institution'] = Craft::t('Institution');
}

However, when I use this method whilst I can add the requisite column to my User table in the admin area and sort the fields alphabetically in ascending order I cannot sort the table by descending order. No errors turning up in the console or site logs. Any suggestions on resolving or debugging greatly appreciated.

Regards,

Cole


texts: How to detect the current report in settings.twig

texts:
I have several reports to create but their settings are going to be very similar.  So I want to use one settings.twig for all of them and detect which report is the current one to show any extra settings.
Something like this pseudo code:

{% set current_report = craft.barrelstrength.sproutreports.current %}
{% if current_report == 'fourth_quarter_payments' %}

{% elseif current_report == 'payments_above_100' %}

{% endif %}

Is it possible to know what the current report is so conditionals can be used in the settings template?


texts: Project Config On or Off for Production Server

texts:
Should Project Config ('useProjectConfigFile' => true,) be set to 'true' or 'false' on the Production server? I have been reading Craft CMS documentation, watching some CraftQuest Lessons,  searching here on Stack Exchange, but have not found a suggested best practice.

I performed a Craft CMS update via the Control Panel Update button with Project Config on. The Update crashed.


texts:
I am trying to set up the URIs for some nested categories in Craft 3 but am having some issues. My structure is basically:

service-one
|-subservice-one-a
|-subservice-one-b
service-two
|-subservice-two-a
|-subservice-two-b

I have set my Category URI Format to:

what-we-do/{slug}

Which is working fine, however I would like the URI for the nested categories to look like:

what-we-do/service-one/subservice-one-a

rather than what I have currently:

what-we-do/subservice-one-a

Is this possible?


texts:
I have uploaded a logo in the General Settings, which I understand changes the logo on the login page.

I was wondering if there was anyway to display this same logo in the site's template?

I know I can achieve this by hard-coding the same URL (but I presume if the logo is changed, this URL will change also.) My other solution is to add a field to a global set but that requires changing the logo in 2 places.

If this isn't possible, how can I retrieve the URL in a plugin? (I have a plugin with a few template helper methods.)

Thanks


texts: Trying to list entries related to users with a specific category selected

texts:
This is a category page. I am trying to display all entries from users with this specific category selected in their account (user field that is a category field type.) This is the code I have so far, but it is not returning results. No errors - just not returning anything unfortunately:

{{ category.title }}

{# Grab all the users who have this category selected (which is a 'category field type' user field) #}
{% set categoryUsers = craft.users.relatedTo(category).limit(null) %}

{# Grab all of the entries by those users #}
{% set categoryUserEntries = craft.entries.section('jobs').relatedTo(categoryUsers).limit(null) %}

{% paginate categoryUserEntries.limit(8) as entries %}

     {% for entry in entries %}

{{ entry.title }}

     {% endfor %}

     {% if paginate.prevUrl %}&laquo; Previous Page{% endif %}
     {% if paginate.nextUrl %}Next Page &raquo;{% endif %}

{% endpaginate %}

Thanks in advance!


texts:
I'm trying to create a craft plugin but I have problems with rendering the settings.

Right now I used the same way like here so this is my plugin code

<?php
namespace Craft;

class testPlugin extends BasePlugin
{

    function getName()
    {
        return Craft::t('Test');
    }

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

    public function getDeveloper()
    {
        return 'Secondred Newmedia GmbH';
    }

    public function getDeveloperUrl()
    {
        return 'http://www.secondred.de';
    }

    public function getSourceLanguage()
    {
        return 'de';
    }

    protected function defineSettings()
    {
        return array(
            'accountID' => array(AttributeType::Mixed)
        );
    }

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

    public function hasCpSection()
    {
        return false;
    }
}

And this is my config.twig

{% extends "_layouts/cp" %}
{% import "_includes/forms" as forms %}

{% set page = 'Settings'|t %}
{% set title = 'Settings'|t %}

{% set content %}

Hello Craft

{% endset %}

But it always ends up like this

The menu is always rendered inside my plugin Settings and If I just use

public function getSettingsUrl()
{
    return 'test/tools/configuration';
}

the template is rendered correctly but I can't pass my variables anymore (of course in that example there are no, but I use some in my real plugin I just didn't want to show you 1000 lines of unneeded code) .

Could you please tell me what I'm doing wrong? My actual real plugin is nearly ready and this is the last error I have to fix but I don't know how. I need your help thank you very much.


texts: Headings Not Shown When Adding Custom Source

texts:
When adding custom sources as per the docs https://craftcms.com/docs/plugins/hooks-reference#modifyEntrySources like so:

foreach($this->regions as $region)
{
    $sources[] = ['heading' => $region['title']];
    $sources['news:'.$region['id']] = [
        'label'    => 'News',
        'criteria' => ['relatedTo' => $region['id'], 'section' => 'news', 'editable' => true],
        'data'     => array('type' => SectionType::Channel, 'handle' => 'news'),
        'defaultSort' => array('postDate', 'desc'),
    ];
    $sources['notifications:'.$region['id']] = [
        'label'    => 'Notifications',
        'criteria' => ['relatedTo' => $region['id'], 'section' => 'notifications', 'editable' => true],
        'data'     => array('type' => SectionType::Channel, 'handle' => 'notifications'),
        'defaultSort' => array('postDate', 'desc'),
    ];
}

the headings are not being shown between the sources. Am I missing something?

UPDATE: Ok, I've managed to figure out that it is to do with ElementIndexSettings. In ElementIndexesService->getSources() is a check for sourceOrder in the settings...

// Should we output the sources in a custom order?
if (isset($settings['sourceOrder']))
...

If I reverse the logic to mimic there being no settings my headings are displayed as expected.

So my question has changed somewhat, firstly is this expected behaviour? If it is I'm only applying these sources for certain users, can I temporarily disable the index settings from within my plugin's init function?

Thanks.


texts: How can you choose which group to output first when using the group filter?

texts: I am using the group filter to group like entries together. I need to be able to control which group is output first. How can I do this?


texts:
I have a front end reg form saving profiles via ajax. All user and profile data is getting stored ok.
The problem comes with validation.

It seems Craft likes to load the errors for certain fields first:

{% macro errorList(errors) %}

So the above fills the error array with username, title and email before processing the others. In ajax am getting the errors like:

function appendErrors(errors) {

$.each(errors, function(field, errors) {
    appendError(field, errors);
});
}

function appendError(field, errors) {
var $errorList = $( '<ul class="errors" />' );

$.each(errors, function(index, error) {
    $errorList.append($('<li>').html(error));
    console.log(error);
});

$("input[name=" + field + "]").after($errorList);
}

I'd like to show all the errors to the user at once on page for sensible UX reasons. So quick brain check - is Craft really doing this? If so, then I see my options like:

Could switch to a pure jQuery/js validation
Could try and manipulate the error array and reindex based on tabindex?
Could try overriding Craft's validation thru plugin

Has anyone else come at this in earnest?


texts: Multiple and or relatedTo in plugin element criteria

texts:
I am trying to return entries that relate to a series of categories.

For example, I am trying to return clothing, in this example, I want to return all entries related to (flannel or denim) and (blue or red) in the products channel.

Flannel, denim, blue and red are all apart of the same category group called: filters, and the category field handle is productFilters

I was trying to return all those entries but it returns 0 entries, any help is appreciated. I know I can do this probably using the craft cms element query in the template but I need to do this in a plugin.

$color_categories = craft()->elements->getCriteria(ElementType::Category, [
    'slug'  => ['blue', 'red'],
    'group' => 'filters'
])->find();

$fabric_categories = craft()->elements->getCriteria(ElementType::Category, [
    'slug'  => ['denim', 'flannel'],
    'group' => 'filters'
])->find();

$entries = craft()->elements->getCriteria(ElementType::Entry, [
    'section'           => 'products',
    'relatedTo'         => ['and', $fabric_categories, $color_categories],
]);

return $entries;


texts:
Is it possible to add an element to the existing assets list and make it sortable

i need it because i have made some modifications that allow to group 2 assets together so generally i now have a list of normal assets added to entries and grouped ones that are wrapped in a div with class pair

i can sort the assets within pairs and assets outside any of the pairs but not the pairs themselves.

In the screenshot you can see that there are two pairs with the purple background. Would it be possible to somehow add them to the sorting flow so i could drag them around as well?


texts:
I need to get a list of variants from multiple products, but in a way that allows us to show the results in Craft's handy {% paginate %} tags.

So far we have this less-than-appealing markup:

{% set firstProduct  = craft.products.relatedTo(category).one() %}
{% set results = craft.variants({product: firstProduct}) %}

{% set products  = craft.products.relatedTo(category).all() %}

{% for product in products %}
    {% set results = results|merge(craft.variants({product: product})) %}
{% endfor %}

However, because we're using merge it's turning our ElementCriteriaModel into an Array. Is there a way to use the {{ craft.variants({product: product}) }} tag and pass it multiple products?

(Craft3 and Commerce2)

Thanks

EDIT: Final markup that ended up working:

{# All products within this category #}
{% set products = craft.products.relatedTo(category).all() %}

{# Empty variant id array #}
{% set variantIds = [] %}

{# Populating variant id array #}
{% for product in products %}
    {% set variantIds = variantIds|merge(craft.variants({product: product}).ids()) %}
{% endfor %}

{# Get all variants from the variant id array #}
{% set results = craft.variants.id(variantIds).orderBy('title asc') %}


texts: Is it possible to reorder fields with drag and drop?

texts:
I'm trying to understand how most people deal with this likely common issue, I've been looking around for answers, apologies if this is a subjective question, but I imagine there is a 'correct way' of doing this and I'm just missing something.

From my understanding Craft is supposed to make implementation and management of content modules very simple, primarily through the use of Matrix fields.

If I want to build a truly modular content management back end, where the user can add any predefined modules of content, and then reorder them with drag and drop, as far as I can see this will have to be done with a matrix field.

So a seemingly clumsy way of achieving this would be define a single matrix field which has all types of content module in as Block types. ie. 'Hero module', 'text columns', 'Latest clients', then in the admin the user adds this global matrix field and adds the required modules.

The problem is the matrix field doesn't seem to be designed to be used like that. If I define a matrix field for the whole page, then a Block within is a module, and within each Block a field is say a title or an image; but if I want to add a position field that image, you can't go down another level - the position would be added to the module, or Block.

Furthermore, I don't understand why it simply isn't possible to create several separate Matrix fields and then drag and drop order them in the page admin. Or any field for that matter.

Thanks, if you need further clarification I can mock up a diagram or something! And I'm on the Craft Slack if anyone would be rather reply on there :)


texts: How do I set up Craft 3 to web server in WAMP?

texts: I'm very new to Craft CMS, and I certainly love this concept! However, I keep trying to run it locally onto my computer following the documentation here https://docs.craftcms.com/v3/installation.html and can never figure out where to go from "Step 5: Set up the web server" for WAMP. Do I need to install Craft into the 'www' folder for WAMP? It's a very bland explanation for this section and cannot for the life of me figure this out! If anyone can assist please let me know as it is most likely something I have missed :( let me know any information that you need to help answer this question.


texts: hi! can you recommend a good basic tutorial for Craft?

texts: can anyone recommend a good video or any tutorial for Craft? Thanks


texts: How do I find the closest parent entry with an Assets field filled in?

texts: I have a structure that goes up to 4 levels deep. Each page has a field for a 'hero' image. If a child page does not have this field filled out I would like to traverse up the structure and find the closest parent entry with this field set. Basically some 'sections' would have a default hero image added to the top level parent while others may have a specific image for each child page.


texts: Can you relate entries from more than 1 section?

texts: Can you relate an entry to entries in two or more different channel/sections?


texts: How to render a template from within a module?

texts:
I'm currently developing a module that contains a custom field and I'd like to create a template to be used in the getInputHtml method.

I try using the Craft::$app->view->renderTemplate method to render a template in the "resources" folder of my module, but Craft does not seem to find the template. How should I specify the path to the template from this module?


texts:
I am relatively new to Craft CMS and have been using the formBuilder2 plugin to create forms. No problem this far. I have been able to use ElementApi to output the forms into Json. Still no problem.
My issue starts when I have to add validation to my form fields. I have read the "The Definitive Guide to Craft Validation for Plugin Developers (The Book)" and I am still very much confused as to how I actually implement validation on specific field in my form. In a nutshell, how can I add a email validator to an field that I named email. Also, how do I implement this to the fieldset if all I have to go with is:

        {% set fields = tab.getFields() %}
        <fieldset class="{{ tab.name |lower|replace(' ', '-') }}">
            <legend>{{ tab.name }}</legend>
            {% for field in fields %}
            {% set input = craft.formBuilder2.getInputHtml(field) %}
            {{ input | raw }}
            {% endfor %}
        </fieldset>
        {% endfor %}

Not to sound silly but why, why, why why????
Please can someone help me....


texts: Entries retain field data that has been removed from entry type layout

texts:
I have a single page section titled "About".  At one point, I had assigned a "text" Rich Text field to the entry type layout.  I then put some filler text in this field and saved the entry.  Later I removed this field from the field layout.

The issue is that craft still populates this entry field on the front-end, i.e. {{ entry.text }} still shows the filler text.

This is problematic for several reasons, but most importantly (in my scenario) because I am working on a search results template which shows an excerpt from each entry; different entries may have different fields available, so I am doing a basic if/else to see what fields may be available, i.e.:

{% if entry.text is defined %}
    {{ entry.text }}
{% elseif entry.multiContent.text is defined %}
    {{ entry.multiContent.text }}
{% endif %}

This raises two questions:

1) Is there a way to tell if an field is actually actively assigned to the entry layout?

2) I understand why the field data would be retained in the database even though the field was removed from the layout, but under what circumstances would populating 'deleted' fields for entries be desired behavior?  It surely adds overhead, it is counter-intuitive (imo) and has the potential to cause all sort of issues.


texts: Why doesn't Craft think the Mcrypt extension is installed?

texts:
I am running the latest version of Homestead, and have installed Mcrypt, but I am getting an error that it is not installed while trying to update a site.

php7.0-mcrypt is already the newest version (7.0.27-1+ubuntu16.04.1+deb.sury.org+1).

This is the php version I am running:

PHP 7.2.0-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Nov 30 2017 13:58:33) ( NTS )

I have rebooted the VM and still get the same result. Is there something else I am missing?

Thank you for any suggestions!


texts:
Is it possible to have both the standard price and sale price visible on the items tiles on a website?

I would like to have both prices visible and wanted to know if this was doable .


texts: How to handle a big amount of whitelabel sites (with multi-site)

texts:
For one of our clients we need to setup a whitelabel template.
I was considering doing this with Craft's Multi site feature which works fine in that way Content management wise.

But, it's probably going to be 50+ whitelabel sites (multi sites) but, I'm afraid this is going to be a mess in the CMS.

Is there another way to handle this issue or, is this the way to go?


texts: Adding link type to Redactor Rich Editor

texts:
I have a Craft CMS powered site which has "Suppliers" set up as a user group. A route is being used to link through to these suppliers on the frontend; example.com/supplier/loremipsum.
Is it possible to add an option to the link button on the Rich editor field, that would allow me to choose a user from the supplier user group? Much like the "Link to an entry" option.


texts: How to set cookie to only show intro animation once per session

texts:
I'm a Craft beginner, so forgive me if this is an easy question.

I have an intro animation, that I'd only like to show on the first visit to the site, so that it doesn't load again when the user navigates back to the homepage after visiting other pages. Then I'd like it to expire when a user closes their browser.

I'd like to use secure cookies via the Cookies Plugin

The id of the intro animation is id="preloader"

I've put {{ setSecureCookie('intro-animation') }} above the html tag and {{ getSecureCookie('intro-animation') }} with the preloader section.

So how I do I set it up to only show the intro animation on first visit?


texts: Shipping and billing addresses dissapear when close and open the page

texts:
I have the following problem. When I set shipping and billing address on my cart and exit the page, the addresses are cleared once I open the page again. Is it possible to disable this behavior?

Thanks,
Kamen


texts: Limiting image rows by 5 but an unknown number of section entries

texts:
I'm trying to limit the total number of images shown to 5. The below clearly isn't correct but gives a rough idea of what i want to do.

One entry could contain 1 image and the next entry 3 images. So i can't set a limit on the craft.entries tag because of the unknown number of images in an entry. It's on the images for loop i want to limit to 5.

{% for images in craft.entries.section('pages').type('events').order('eventDate desc').eventDate('<=' ~ now).search('gallery:*') %}
    {% for image in images.gallery.limit(5) %}

    {% endfor %}

{% endfor %}


texts:
Is it possible to check the status of entries linked to in content from the Rich Text field? For example, the user might create a link in a paragraph to an entry that is in draft status. I would like to only display an actual link in the front end if this entry is then published.

Is this currently possible?


texts: Best Approach to all unique groups of users to edit unique groups of entries in 1 channel

texts:
I've got a request to let front end users edit entries in 1 section, but only if the entries are related to their user group - so different users will have ability edit a different subset of entries in the same section.

group A could edit entries 1,3,10,12
group B could edit entries 2,5,7,14
group C could edit entries 9,11,21

Site admins need to be able to add new groups regularly
Thinking about using a category assigned to both user and entry and on the front end limiting which entries they have access to edit by checking for relationship to that category.
Is this a feasible approach? Is there a better approach.

Also looked at the User Group plugin, but that relies on actual user groups which site admins won't be able to add on the live sites since allowAdminChanges is set to false to prevent issues with project.config being updated out of git.
Thoughts


texts: Is there a way to retrieve the type of an entry?

texts:
To be more specific, I would like to know if an entry is a Single or part of a Structure or Channel.

entry.type seems to return the name of the single or section.

Is there a way to retrieve this information for every entry?


texts: How do I display tags comma separated with "and" between the last two tags?

texts:
I would like to output a tag-list like this:

foo, bar and baz

I know how to elegantly output a tag list with no comma after the last tag:

{% for tag in tags %}
    {{ tag }}{{ not loop.last ? ', ' }}
{% endfor %}

Is there a similarly elegant solution for getting the tags to display the way I want?


texts:
Example: I have content which could be separated into Big News and Small News.

The Big News has much text (which would need a link to its own entry). The Small News has only one text block (so it wouldn't need a separate page for each news).

Whats the best way of handling this? Two separate channels?

One channel with two entry types and a template with a conditional:

{% if entry.type == 'SmallNews' %}{% exit 404 %}{% endif %}

How do you handle this? I guess it is not possible to add These entries have their own URLs based on entry types, right?


texts: Image driver error: "Class 'Imagine\Gd\Imagine' not found"

texts:
I recently migrated an inherited site to a Digital Ocean VPS (LAMP, PHP 7.2, Craft 3.4.9). When I visit /admin/utilities/system-report I receive the following error: Class 'Imagine\Gd\Imagine' not found. Attempting to upload an image results in the same error. Existing assets are fine on the front-end but cannot be edited and thumbnails are not being displayed in the CP.

PHP info reports that both gd and imagick are enabled.

I've tried adding the drivers to general.php ('imageDriver' => 'gd' and 'imageDriver' => 'imagick') without success. Interestingly, there are two other Craft sites on the server that are working as expected -- the setup of all three are identical.

Stack trace follows.

Error: Class 'Imagine\Gd\Imagine' not found in /var/www/[redacted]/vendor/craftcms/cms/src/utilities/SystemReport.php:98
Stack trace:
#0 /var/www/[redacted]/vendor/craftcms/cms/src/utilities/SystemReport.php(75): craft\utilities\SystemReport::_appInfo()
#1 /var/www/[redacted]/vendor/craftcms/cms/src/controllers/UtilitiesController.php(85): craft\utilities\SystemReport::contentHtml()
#2 [internal function]: craft\controllers\UtilitiesController->actionShowUtility('system-report')
#3 /var/www/[redacted]/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#4 /var/www/[redacted]/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#5 /var/www/[redacted]/vendor/craftcms/cms/src/web/Controller.php(178): yii\base\Controller->runAction('show-utility', Array)
#6 /var/www/[redacted]/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('show-utility', Array)
#7 /var/www/[redacted]/vendor/craftcms/cms/src/web/Application.php(291): yii\base\Module->runAction('utilities/show-...', Array)
#8 /var/www/[redacted]/vendor/yiisoft/yii2/web/Application.php(103): craft\web\Application->runAction('utilities/show-...', Array)
#9 /var/www/[redacted]/vendor/craftcms/cms/src/web/Application.php(276): yii\web\Application->handleRequest(Object(craft\web\Request))
#10 /var/www/[redacted]/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#11 /var/www/[redacted]/web/index.php(21): yii\base\Application->run()
#12 {main}

EDIT: The solution, as provided by Brad in the comments, was to delete composer.json along with the vendor directory and then run 'composer update'.


texts: Combine variables with text to make variable

texts:
How can I create a variable that is a combination of two variables with text?

For example, I know the following is wrong but is something like this possible:

{% set foo = 'foo' %}
{% set bar = 'bar' %}
{% set foobar = 'Hello' foo,bar %}
{{ foobar }} #Outputs Hello foobar


texts: Deleting a user's profile photo via frontend in Craft3

texts:
I am having the hardest time allowing a user to delete their profile photo with Craft3. I have tried to follow this thread's answers : Allow user to change or delete their photo for their profile from the front end. But it is not working. I guess because some stuff has changed since Craft2.

Here is my twig code :

    {% if isEditable %}
        <form method="post" enctype="multipart/form-data" accept-charset="UTF-8">
            {{ csrfInput() }}
            <input type="hidden" name="action" value="users/save-user">
            {{ redirectInput('profil/'~currentUser.id) }}
            <input type="hidden" name="userId" value="{{ currentUser.id }}">

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

                        {% for error in errors %}

{{ error }}

                        {% endfor %}

                {% endif %}
            {% endmacro %}

            {% from _self import errorList %}

            <input type="hidden" name="deleteUserPhoto" id="deleteUserPhotoInput" value="">
            {% if account is defined %}{{ errorList(account.getErrors('deleteUserPhoto')) }}{% endif %}

                        Modifier ma photo de profil

            <input id="profilePhotoInput" type="file" name="photo" accept="image/*">
        </form>

        delete

    {% else %}

    {% endif %}

And the Javascript code :

$('.delete-profile-photo-btn').on('click', function () {
    var deleteUserPhotoInput = $("#deleteUserPhotoInput");
    deleteUserPhotoInput.val('1');
    deleteUserPhotoInput.parents("form").submit();
});

With this code, I get no errors, and the profile image doesn't delete.

I then decided to try and reverse engineer the admin panel and see how it was done there. I came up with the following form :

<form id="deleteUserPhotoForm" method="post" enctype="multipart/form-data"
      accept-charset="UTF-8">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="users/delete-user-photo">
    {{ redirectInput('profil/'~currentUser.id) }}
    <input type="hidden" name="userId" value="{{ currentUser.id }}">
</form>

And the Javascript :

var form = $('#deleteUserPhotoForm');

var data = form.serialize();
userFormAjaxCall(data, function (status, resp, xhr) {
    console.log(status);
    console.log(resp);
    window.location.reload(true);
});

With this code, it seems to work, but I get this error message (not sure what the equivalent in english is).

  Impossible de trouver le modèle “users/_photo”

What is the cleanest and simplest way I can allow a user to delete their profile photo?


texts: How to determine if there are events in a calendar?

texts:
I need to write a conditional that determines if events actually exist in a calendar. I only want to display an option in the the select dropdown IF the calendar has events:

{% set calendars = craft.calendar.calendars({
    limit: 100,
    order: "name",
    sort: "asc"
}) %}

{% set events = craft.calendar.events({
    calendarId: calendar.id
}) %}

{% for calendar in calendars %}

    {# determine what the URL should look like based on the current URL structure #}

    {% if segment1 == '' %}
        {% set urlPart = "month/calendar/" ~ calendar.handle ~ "/" ~ month.date.format('Y/m') ~ "#1" %}
    {% elseif segment3 is not empty and segment4 is not empty %}
        {% set urlPart = "month/calendar/" ~ calendar.handle ~ "/" ~ segment4 ~ "/" ~ segment5 ~ "#2" %}
    {% else %}
        {% set urlPart = "month/calendar/" ~ calendar.handle ~ "/" ~ segment2 ~ "/" ~ segment3 ~ "#3" %}
    {% endif %}

    {# I need a conditional here that outputs an option only IF there are events in the calendar #}

    {% if events %}
        <option value="{{ siteUrl }}cal/{{ urlPart }}"{% if segment3 == calendar.handle %} selected="selected"{% endif %}>
            {{ calendar.name }} - {{ calendar.event.occurrenceCount }}
        </option>
    {% endif %}

{% endfor %}

UPDATE: I expanded this out so you can see everything. Unfortunately, this is still outputting all calendars even if the calendar has no events.


texts:
Can not seem to set a redirect path after a password reset, using Craft 3.5.1 - I have done this many times on other sites, but all of them are on earlier versions of Craft.
I have a frontend form for password reset, and the link in a reset password email gets you there. However, once the password is reset it redirects to the home page.
This is what I have in my config/general file:
'setPasswordSuccessPath' => 'login',

After troubleshooting for a while I tried copying the password reset link in the backend, used it to go the reset page and then setting a password. That worked - after setting the password I was redirected to my setPasswordSuccessPath ! But it never works when an automated email is sent after creating a new user.
Am I missing something?


texts: Environmental variables for Scout plugin in scout.php file

texts:
I was wondering if it was possible to add .env variable for the indices area in the scout.php file?

I added this to my .env file

SCOUT_INDICES = "search_SCOUT_DEV"

Then this to my scout.php

\rias\scout\ScoutIndex::create('getenv(varname:’SCOUT_INDICES’)”)

To replace

\rias\scout\ScoutIndex::create('search_SCOUT')

Which is my Prod indices. It did not work.


texts: Structure entry connected to multiple parent entries

texts:
Is there a way to connect one structure entry to multiple structure entries?

Like:

(wonderfully drawn image represents the connection of Food Festival to both structure entries)


texts: Posting remotely - to fields in a channel or a plugin's fields?

texts:
Been looking at porting a site from EE to Craft.

We have a custom module that accepts a POST and then stores that data in fields in a particular channel. The mappings are stored in extension settings so there are no hardcoded field IDs in the module code.

In Craft, how would we go about that? I can see that we'd need to have a controller method that would be publicly accessibly but am unsure if we can easily use Entries or if we need a custom table with fields, field layout etc.

The use case is a job board. Jobs are just entries in that they have a job title, body, summary, salary range, blah blah blah, and CMS users should be able to create jobs in Craft, so just a channel looks fine. The only addition is that a third party needs to post data to the channel to create jobs too, hence the need for the plugin.

Can you please advise the best approach here? The bit I'm stuck on is either creating mappings in the plugin settings that link the posted data with fields created in the channel, or on showing a template where the CMS user can create and edit jobs using the standard Craft field layout UI.

Hope that all makes sense!

Thanks


texts: Safely calling other plugin code from a different plugin

texts:
I have a Craft Plugin that is a logging library I want to use in other plugins I develop, but I don't want it to be a dependancy in these other plugins. Is there a nice, space efficient way in Craft to do something like below? I don't want to have to wrap every call in an if statement:

# If WatchTower isn't installed... don't explode please!!!
@craft()->watchTowerDB->log($params)

My plugin seems to stop processing and redirect to the current page if it isn't installed. Thanks!


texts:
What is the best way to set a logic order on a channel of entries. I'd like to be able to set the order of each entry (any unset can default to date afterwards).

Would the best way be just a text field and enter a number? Or is there some other structure?


texts: Create several subcategories without using the GUI in craft

texts:
I have to create the following categories hierachically : One book has between 1 and 150 chapters.
I have to do this for several books.  Dealing with chapters is painful using the GUI. Is there any way to achieve this directly using json, queries ?

Category "Book 1" is consisted of 100 chapters subcategory

Book 1 -> Chap 1
Book 1 -> Chap 2
...
Book 1 -> Chap 100

Category "Book 1" is consisted of 10 chapters subcategory

Book 2 -> Chap 1
Book 2 -> Chap 2
...
Book 1 -> Chap 10


texts: Modify how the html fields are outputted by Redactor

texts: Is there a way to modify how the html fields are outputted by Redactor? I'm creating an email template and I'm trying to add inline styles to Redactor's list items, links, etc.


texts: Impossible to invoke a method on array. How to merge multiple objects and keep as objects

texts:
{% set newsletterImages = newsletter.imagesCongratulations|merge(newsletter.imagesCis)|merge(newsletter.imagesSection3) %}
{% set transformedImages = newsletterImages %}

{% for image in newsletterImages %}
  {{ image.title }}<br />

{% endfor %}

newsletterImages is merging images from 3 different global fields.
I want to then randomise and only output 6 of these images.

However, when I try

{% set transformedImages = newsletterImages.orderBy('RAND()').limit(6) %}

I get the error: Impossible to invoke a method ("orderBy") on an array. and Impossible to invoke a method ("limit") on an array.

Can anyone help point me in the right direction to achieve this?


texts: In my particular case I need to be able to switch the layout that the template extends. Is this possible to do using locales?


texts: Access Matrix field that is assigned to a user

texts:
Using Craft 3.

I created the following field:

myMatrix which has Field Type = matrix
and is part of the group myGroup

This is composed of one block:

myMatrixBlock
with 2 fields:

myMatrixField1

myMatrixField2

I have assigned the myMatrix field to Users using the control panel (user settings >> fields).

How do I

Access the data in myMatrix from my twig template?  I'd like to get all the data in this matrix for the current user and loop through it and display data for each myMatrixField1 & Field2.  I can't figure out how to retrieve myMatrix field.
How do I create a new record in the myMatrix field? I'd like to create a new entry in the myMatrix field and store data for the current user in each of the fields.

I've been searching at this for several hours now ... I feel this must be VERY easy but I can't seem to figure it out.  Also, if you have a link to documentation on functions/variables that are available for each object at the template level I'd be grateful.  I can't seem to find that in the docs either.

Thank you!


texts: Sending a custom email in the users prefered locale

texts:
Usecase:

I'm sending out custom emails based on certain events to my users. These users have chosen a certain prefered locale in their profile settings and I'd like for those emails to be in that locale instead of in the locale of the control panel at the time of triggering the events.

So what I'm looking for is a way to set the relevant locale before rendering the email template with twig but I cant seem to find a way.

Relevant code

$mailer = craft()->email;
$mailToBeSent = new EmailModel();

craft()->templates->setTemplatesPath(CRAFT_TEMPLATES_PATH);
$mailToBeSent->toEmail = 'some.email@domain.com';

$mailToBeSent->subject = $subject;

$content = craft()->templates->render(
   '_emails/notification',
    [
        'userInfo' => $this->generateUserInfo($newUser),
    ]

);

$mailToBeSent->htmlBody = $content;
$mailer->sendEmail($mailToBeSent);

Let me know more information is needed or if something is unclear.


texts: How to show events for "This Weekend, Next Week"

texts:
Stemming from this original post I was able to show Events using a custom date field and successfully got "Today" and "Tomorrow" events to show up.

How would I go about doing some custom Math to show "This Weekend" or "Next Week" events? I'm sure I have to first write a conditional on determine what the current Day is, but not sure the best way to do this.


texts: Feed Me with Related Entries Fields - One to Many Relationship

texts:
I'm using Feed Me to populate content for a "Meetings" section in my site. One of the fields in this section is "Meeting Attendees", which is an entries field relating to a Contacts Section.
I have a JSON file that contains a unique Meeting ID, and this Meeting ID could map to several Contacts. In a simplified form, my JSON file format is essentially this:
[
    {
        "Meeting Title" : "Project Kickoff"
        "Meeting Attendee" : "John Doe"
    },
    {
        "Meeting Title" : "Project Kickoff"
        "Meeting Attendee" : "Jane Smith"
    },
    {
        "Meeting Title" : "Project Kickoff"
        "Meeting Attendee" : "Jim Brown"
    }
]

You'll see in this simplified example that three Contacts need to be related to the "Project Kickoff" Meeting entry. I have my "Meeting Attendees" entries field configured with no limit on number of selectable entries, and can add multiple entries without issue when entering data manually.
However when I run Feed Me on a data set like the one above, Feed Me seemingly overwrites/replaces the entries rather than adding each as a separate relation. e.g. When Feed Me has completed processing the above dataset, my "Project Kickoff" entry will only have one attendee related ("Jim Brown" in this case - or whatever the last value in the dataset happens to be). For the example data above, I would expect to see all three "Meeting Attendees" names related to the "Project Kickoff" meeting entry.
Is there a way to configure either Feed Me or my JSON data to produce the intended result?


texts: Single entry with 450 Matrix blocks throwing error on save

texts:
A client has a Singles entry with a Matrix block defined that contains a few text fields, and one image field. They've created approximately 450 instances of this Matrix block, and can no longer update the page. Craft throws a 500 error. Craft logs just show a basic

exception 'Craft\HttpException' in /srv/[clientName]/releases/20170418025256/craft/app/controllers/TemplatesController.php:59

and nothing of use in the Apache error logs. Anyone have experience with this sort of error, or confidence that this would be a Craft bug?


texts:
I have a frontend form to save an entry which includes a file upload input field:

<input type="file" name="fields[newsFile]">

The upload works fine, but is it also possible to set the title of the asset similar to the backend? Unfortunately, this doesn't work:

<input type="text" name="fields[newsFile][title]" value="Asset Name">


texts: Can't seem to get reverse relational field working from within a Neo field

texts:
Has anyone managed to get reverse relations from a Neo field working? I have a Neo field containing an Entries field which works fine on the page/section entry where I have the Neo field, but I’m trying to get data out on that related entry page. Might just be bad coding on my part!

I've tried a simple test using a standard Matrix field and the reverse relation works fine, here's that working code:

{% set matrixRelatedEvents = craft.entries.section('events').relatedTo({
    targetElement: entry,
    field: 'matrixField'
}) %}

This is my Neo reverse relation code which is currently not working:

{% set neoRelatedEvents = craft.entries.section('events').relatedTo({
    targetElement: entry,
    field: 'neoField'
}) %}

Any ideas or is it not possible?


texts:
I click on fullscreen button in redactor, However, an error in the console enter code here this.fullscreen.enable is not a function. And on enter click or paste text in new paragraph is added  ???
In general, there are not the best impressions of working with the editor.


texts:
I am totally newbie in Craft CMS so don't be harsh to me.

While coming to my problem I am getting Error : 404 while installing Craft CMS on my local server Linux Mint OS please someone guide me to install Craft CMS successfully on my local server,I followed below basic steps..

Created db gave db details in db.php.
Renamed htaccess to .htaccess.

My folder structure was

/var/www/html/Craftdemo/craft and public

  My local server configured correctly and is working good enough to run
  my other sites like Wordpress/Magento and some JS files.

Thanks in advance


texts:
I'm trying to submit entry data via AJAX (using Guest Entries plugin) following what's written in a similar question, however even though I am not sending the data in JSON format, the data does not seem to want to save and keeps returning a "cannot be blank error" for every field submitted.

{"errors":{"title":["Title cannot be blank."],"add01e":["Email cannot be blank."],"firstName":["First Name cannot be blank."],"lastName":["Last Name cannot be blank."]}}

These are, in reality, are being submitted as can be seen below. What's strange is that the sectionId and action are being processed for the server to respond with the latter list of errors.

Sent Form Data Source:

action=guestEntries%2FsaveEntry&sectionId=14&firstName=asdsa&lastName=dsad&add01e=asd%40sd.com&companyName=asd&redirectUrl=%2Fcontent%2Fdownloads%2Fproducts%2Fstrokepad%2F6pm-strokepad-brochure-a4_web_300115.pdf&title=Download+Request

Sent Form Data Parsed:

action:guestEntries/saveEntry
sectionId:14
firstName:asdsa
lastName:dsad
add01e:asd@sd.com
companyName:asd
redirectUrl:/content/downloads/products/strokepad/6pm-strokepad-brochure-a4_web_300115.pdf
title:Download Request

Other details related to the request:

Request URL:http://craft.dev/
Request Method:POST
Status Code:200 OK

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

JS performing the ajax request:

var formData = $form.serializeArray();
formData.push({name:'title',value:'Download Request'});
$.post('/', formData , function(response) {
    if (response.success) {
      //On Submit Success
    }else{
      alert('An error occurred. Please try again.');
    }
});

Any idea what I might be doing wrong?

Thanks in advance!


texts: Set navigation menu item to active for child pages

texts:
Currently we're highlighting the active page in our navigation by having a structure of menu items with a "menuLink" field and comparing that to the current entry uri. Something like this:

{% nav link in Menu %}

        {% if link.menuLink|length %}
            {{ link.title }}
        {% else %}
            {{ link.title }}
        {% endif %}

{% endnav %}

However, this doesn't work for children of structures or channels. We could change the if statement to look for the entry.uri OR the entry.section as below but obviously that only works if the section/channel has the same name as the link.slug:

{% if link.slug == entry.uri or link.slug == entry.section %} class="active"{% endif %}

I searched through the previous questions but all the answers to this problem seem to involve reading a section of the URL but we want to be able to control the URLs and have some structure children have a top level URL rather than a /structure-name/{slug}

If we could have a field on the structure itself to say which menu item to highlight then you could just say something like

if entry.section.type == channel or structure then active menu item = entry.section.menuItem

but you can't have a field on a structure/channel as far as I'm aware?

Does anyone know of a way of solving this problem without the use of URL segments?


texts: No more Ajax in the control panel after update to Craft 2.7.0

texts:
I've update a Craft 2 site to Craft 2.7.0 but since I did no Ajax(?) calls work; I can't clear caches, backup data bases, open a Matrix field,...
Anyone got an idea what went wrong?
Thanks!


texts: OAUTH/Social Poster can't connect to facebook: "Can't load URL..."

texts: I've seen others having this issue with no solutions either but still need to put it out there. What is it I'm missing here? I seem to have everything setup correctly.


texts: Sales that select both Product Types and Specific Products in the Conditions

texts:
Is it correct to assume that if I set up a Sale with some Specific Products in the Condition, it will not have any effect to also select Product Types in the Conditions of that sale?

i.e. If I select both Product Types and Specific Products, does the sale apply to all the products in the selected types, and also to the selected specific products, or (my current understanding of the "correct behavior") would that sale apply to only the selected specific products?


texts: How can I get the parent category group via the category to create multiple relation criteria?

texts:
I have two category groups: Cars and Colors

My Cars category looks like this:

Cars
    Sports Cars
        Corvette
        Lamborghini
        Porche

My Colors category looks like this:

Colors
    Red
    Black
    White

I have two drop-down menus; one to choose the car, the other to choose the color.

I can choose the car, or the color just fine. My url's look like this:

mysite.com/cars/corvette/
- or -
mysite.com/cars/red/

It's when I need to relate both categories. Since my two category groups have different levels, I'm not sure how to get the parent group of Colors from red. Which is what I think I need in order for the relatedTo to work properly.

For example, a url might look like this:

mysite.com/cars/corvette/  {# no problem #}
- or -
mysite.com/cars/red/       {# no problem #}

I'm able to get to the categories on my template:

{#
 # Get the primary category GROUP via url segment.
 # Example: Cars
 #
 #}
{% set primaryCategoryGroup = craft.categories.slug(craft.request.getSegment(2)).first() %}

{#
 # Get the primary CATEGORY via url segment.
 # Ex: Corvette or Red
 #}
{% set primaryCategory = craft.categories.slug(craft.request.getSegment(3)).first() %}

Then I check if I need to compare both relationships:

{% if craft.request.getSegment(4)|length %}
      {% set secondaryCategorySlug = craft.categories.slug(craft.request.getSegment(4)) %}
      {% set secondaryCategory = craft.categories.slug(craft.request.getSegment(4)).first() %}

      {{ secondaryCategory.title }}  {# Red or Corvette #}
      {{ primaryCategory }}  {# Red or Corvette #}

      {# Begin the fail #}
      {% set entries = craft.entries.section('mySection').relatedTo('and',
          { sourceElement: secondaryCategory, field:'title' },
          { targetElement: primaryCategory }
      ) %}
{% else %}
    {# Only get single relationship. #}
    {% set entries = craft.entries.relatedTo(primaryCategory) %}
{% endif %}


texts: How to setup the structure in Craft for a Property Development site I'm building

texts:
I've been designing and building a property developers website for the last 9 months (client delayed building it due to economic reasons), but now we are at the point where it's ready to be built into Craft, as I've finished the HTML/CSS/JS build after the 3 months of hard work.

But due to the client budget I'm attempting to do the Craft build myself (I'm a designer with good CSS etc, but this is my first Craft build), so I'd appreciate a bit of advice on the best approach, as I've tried a number of different approaches so far, but am really struggling, as the development section of the site has multiple levels, and I need to set it up in a way that is going to be idiot proof for the client to be able to add new developments, and all the associated properties with each development.

The Development section structure is as follows:

**All Developments** (listing page per development)

--**County** (for example "Berkshire") - A similar listing page for properties only in Berkshire.

----**Development Overview** - Information about the whole development)

------**Available Properties** - A listing page for all of the individual plots in the development

--------**Plot Page** - individual plot information including floorplans, specifications, images etc

These are all linked via breadcrumbs as well.

There are around 15 developments currently, and some have 50+ plots in them. So there could be hundreds of plot pages.

So the client is going to need to be able to create the Development Overview page in the CMS each time, and all the individual Plot pages per development, and also add the Available Properties page once there are plots, and each development will need to be related to the county they are in, and pulled into the listing page at the top level too.

So would appreciate some experienced advice on the simplest approach that is going to be easy for the client to manage.

And also any other recommended resources for learning as I've already been through all of the mijingo video courses, and still struggling as this developers site is much more complicated than any of the tutorial sites, which only have basic relationships.

One final thought I had, is would this be easier to do with Craft commerce? As the development section is very much like a ecommerce site in structure, but without the need for the payment stuff. Or can standard Craft handle it?

Kind regards


texts: Simplify templating query with Super Table

texts:
The following code will return the correct result, but since I'm quite new with Craft, I wanted to know if there was a more preferred/efficient way to filter this in the template (or maybe create a custom function).  Here we go:

{% set currentDay = now|date('l') %}
{% set currentTime = now|date('H:i') %}
{% set entries = craft.categories.group('shows') %}

{% for entry in entries %}
  {% for row in entry.showschedule %}
    {% for day in row.airingDatesEn %}
      {% if day == currentDay|lower %}
        <li>{{ entry.title }}</li>
      {% endif %}
    {% endfor %}
  {% endfor %}
{% endfor %}

As you can see I'm looping over all the entries in the craft category 'shows', then looping over the SuperTable row showschedule, then looping over the checkbox category airingdatesEn to see if it contains the current day.

Seems like I'm doing a lot of barrel rolls here, any ideas on how to simplify?

Thanks!


texts: Organize filtered entries by a specific category

texts:
I have an array of products that has already been filtered by a brand category. I want to display them in a list ordered by a size category. This is working, but I think there must be a better way:

{% set productList = craft.entries(params) %}
  {# where params includes a relatedTo parameter already #}

    {% for size in sizes %}
        {% for product in productList %}
            {% if product.sizeCategory.first.id == size.id %}
                {{ product.title }}<br />
            {% endif %}
        {% endfor %}
    {% endfor %}


texts: Defining elements of a research project as assets or entries?

texts:
May be over thinking this but I wonder if anyone else has had to deal with a similar issue.

I am building a site which holds my PhD research. The main type of assets I'll be presenting are:

Sketches
Audio files
Videos
Video Links

I'm am going back an forth between 1) creating individual entries for each asset , defining t's type and linking to the file 2) Adding fields to the assets themselves.

The benefit of 2) is I have no need to create unique entries which feels like additional work. The main drawback of 2) is I have no way of managing youtube links (or other links to external files) as an asset as no physical file exists in craft. I would ideally like to manage all these research elements in the same way.

These element can be viewed in various ways in craft through relatedTo. Which will allow sketches to be viewed in a sketchbook as individual sketches to be viewed in relation to a project. It seems that having them as entries (1) would make this easier, but I may be wrong.

Anyone any thoughts on this problem?

I response to Mats:

The plugin you suggest sounds perfect, Thanks.

As a specific example One type of research is a design journal. Each page is made up of a scan of the actual paper journal, Metadata, perhaps a few notes. All of which can be added to the asset. I have 2 options to create the book:

Using a structure:

Book (Entry type of Journal)
--Page 1 (Entry type of Page)
--Page 2 (Entry type of Page)
-- etc

Or, an entry with a matrix

Book (Entry type of Journal)
-- Pages (Matrix field)
---- Page 1 (Matrix block)
---- etc

But, the journal is only useful in that form so it can relate back to a physical copy (which will be handed as evidence). The pages although chronological don't necessarily represent a narrative flow. The narrative comes when I create a separate type of entry, a research project which is a way of pulling together all of the different elements. I would look something like:

-Research Project
-- Overview
-- Related Journal Pages
-- Related Audio recordings
-- Related Articles
-- etc

If the journal were a structure it would be easy to use an entry field in the Research Project, select individual pages and get the name of the journal it's in (it's parent). I'm using ManytoMany plug-in to create a 2-way relationship, so when viewing journal pages you would also see what projects it's mentioned in.

If I went the matrix approach it would be tidier. But, i could't link the Project to the Matrix Block (page) within a journal. I'd instead have to relate it to the original asset. Which would be fine, but instead of a simple parent.title to get the journal name displaying on the Project page. I'd have to run another query to find what journal the asset is related to. Which seem a bit.. unsatisfactory.

I'm not so concerned about not having a unique url for the asset. I'd probably display them from the parent page in 2 ways 1) Thumbnail grid to lightbox slideshow. 2) paginated results.

I'm not sure I've come to any conclusions with this bit or writing. I hoped I would. a) Structure and slightly necessary asset wrapped in an entry or b) asset simplicity and slightly more complicated way of simulating a parent structure ... hmmm.


texts: Can I add a custom canonical URL to a page if also using SEOmatic?

texts: SEOmatic puts a canonical on every page. But some pages I need to be able to add a custom canonical, but not sure how to overide SEOmatic's otherwise there will be two.


texts: I have a record so I can save my data to the DB but do I need a model for services and stuff ? Or can the record do that too ?


texts: Grouping by Date (Day) Not Working Correctly

texts:
For a week-long schedule, I'm trying to group events that occur on the same day, and also fall into one of two classifications— they are free if a pass is purchased or not included in the pass.

{% set passEvents = craft.entries.section("event").eventForwardPass("No").find() %}
{% for date, entries in passEvents | group("eventStartDate|date('F d, Y')") %}

ONLY list Non-Forward Pass events.

{{date}}

      {% for entry in passEvents %}

{{ entry.title }}- {{entry.eventStartDate}}

      {% endfor %}

{% endfor %}

I'm only showing the date next to the title to verify when the code works properly. The problem I'm having is this code seems to return all entries that match the 'set' criteria under each date, rather than just the entries that match the 'set' criteria for that particular date.

I'm basing the code off of examples that would normally group by month or year. It seems like I'm asking for the right things, but obviously, the results tell me, that I'm asking for the wrong thing on the loop.


texts: Bad Request POST param “redirect” was invalid

texts:
I'm creating a user profile form on the front-end of our website. I've removed all template code and replaced it with the documentation code from the Craft website. I updated the docs code to reflect fields that we're using, rather than the example fields.

Upon clicking the Save Profile button, the next thing I get is this error:

**Bad Request**

POST param “redirect” was invalid.

I've changed the redirect action input to multiple values, but none work.

I'm running Craft 2.6.3008.

Update: Here's the form:

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="account/profile?m=updated">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">

    First Name
    <input type="text" id="firstName" name="firstName" value="{{ currentUser.firstName }}">

    Last Name
    <input type="text" id="lastName" name="lastName" value="{{ currentUser.lastName }}">

    <input type="submit" value="Save Profile">
</form>

The form is located at account/profile. I'm asking it to return to the same template, just with a parameter appended to the address to verify the form was updated.


texts: Craft assets indexing wants to remove files that still exist

texts:
Launching the task Update Asset Indexes in CP Settings / Tools.

At the end of this task Craft propose a dialog box for you to check some missing files that has been removed from the asset source/folder.

But for some reason my Craft is constantly asking me to remove some files that still exist in folder. And if I click OK then it ask me on each indexing task to remove a randomly chosen file.

One interesting clue is that this bug does not happen locally on my Mac Yosemite / MAMP local dev.

Charset and Collation look right to me:

Any idea how to fix that? (server/mysql config?)
Very annoying for me because I got metadata attached to assets so I cannot permit random deletion. It also remove the asset files inserted into entries.


texts: Losing focuspoint on saveEntry by plugin

texts:
I've implemented a plugin for synchronizing an external Database into my Craft project which also includes images.

Those images have a focuspointer but i lose the focuspointer onSaveEntry by my plugin.
(I'm using the Focuspointer Plugin)

Note: I only lose the focuspointer when updating an entry by my plugin, updating an entry by control panel works fine.

This is the code from the focuspointer plugin where the focuspoint get's deleted:

public function onAfterElementSave()
{
    craft()->focusPoint_focusPoint->deleteFocusPointRecordsByFieldIdAndSourceId(
        $this->model->id,
        $this->element->id
    );

    $hash = spl_object_hash($this->element);

    $value = isset($this->values[$hash]) ? $this->values[$hash] : null;

    if ($value && isset($value["focus-attr"])) {
        $i = 0;
        foreach ($value["focus-attr"] as $focus_attr) {
            craft()->focusPoint_focusPoint->createOrUpdateFocusPoint(
                $focus_attr["data-focus-x"],
                $focus_attr["data-focus-y"],
                $value[$i],
                $this->model->id,
                $this->element->id
            );
            $i++;
        }
    }

    parent::onAfterElementSave();
}

How can I prevent the loss of the focus point onSaveEntry by my plugin?


texts: Events pages that are linked to venues crash when the venue entry is disabled

texts:
I have 2 channels, "events" and "venues". Using the entries fieldtype in the "event" entry a "venue" where it takes place is selected. However, if the venue entry is disabled, rather than the event not showing, a fatal error kills my page.

Is there a way of somehow querying events that doesn't return entries linked to disabled venues? I'm guessing doing something with relatedTo but not sure how to go about it.

{% set qDisplay = craft.request.getParam('display') %}
{% set qFilter = craft.request.getParam('filter') %}

{% if qDisplay == 'all' %}

    {% paginate craft.entries.section('events').status('live,pending').order('postDate asc') as entries %}

{% elseif qDisplay == 'month' and qFilter != null %}

    {% set startDate = now | date_modify('first day of ' ~ qFilter) %}
    {% set endDate = startDate | date_modify('+ 1 month') %}
    {% set entries = craft.entries.section('events').postDate('>= ' ~ startDate).expiryDate('< ' ~ endDate).status('live,pending,expired').order('postDate asc') %}

{% elseif qDisplay == 'venue' and qFilter != null %}

    {% set entries = craft.entries.section('events').relatedTo(qFilter).status('live,pending').order('postDate asc') %}

{% else %}

    {% paginate craft.entries.section('events').status('live,pending').order('postDate asc') as entries %}
    {# set entries = craft.entries.section('events').status('live,pending').limit(6).order('postDate asc') #}

{% endif %}


texts: Global-only fields adding columns to content table?

texts:
I understand the rationale of adding one column per custom field to the craft_content table in the database; but why would this happen for fields that are only used once globally?

Is there a way to define global fields without adding to the entire content table?

Perhaps a better option would be to define a single "Options" matrix field which can be used anywhere, and then use that to store zero-or-more options?


texts: How to loop through a table and set variables based on the existence (or not) of data in those tables?

texts:
I am using a table field in Craft (price) limited to one row only, used to manage price setting in different currencies on an entry. The three cols each contain number fields with the handles dkk, euro, and usd respectively. (note their column order here can be used to infer a preference later which is useful)

At the template level I am also setting a variable pricepreferredCurrency to specify the currency we want to use for conversions when required. This could be moved to the cp later I guess but it's barcoded at the template level for now.

{% set preferredCurrency = euro %}

If at minimum one price is set I would like to display the price in all three currencies, but I am struggling to create template logic needed to (smartly) support the following functions:

If any price is explicitly set, use that price and do not unset or
recalculate the price based on other prices or currencies. Just take the input at face value.
Otherwise, if a price is empty or unset but at least one other price is set, use the next available price that is set as the price to convert from (using preferredCurrency as the basis for that conversion)
If no prices in any currencies are set, exit and show no prices.

I have already worked out the conversion between currencies, but I am having trouble looping through and making good decisions and logic to handle the different cases. If I can get to the cases I can handle the rest I think.

I feel like this is probably very simple and could even be abstracted I am sure to loop through an expanded set of currencies (without the need to get explicit) but that is beyond me.

I am also open to completely other ways of doing this in craft. Maybe it is better to move currencies into a category group.

I think ultimately I will make decisions about which price to show based on some geolocation, but now I am ready to calculate (where needed) and surface all three. Your help/advice as always much appreciated.

You can see I started to work through this and could immediately tell I was off on the wrong foot. This is really embarrassing to share but...

{% for row in entry.price %}
{% set preferredCurrency = DKK %}

{% set priceDKK = row.dkk %}
{% set priceEURO = row.euro %}
{% set priceUSD = row.usd %}

{% if row.dkk is not empty %}
  {% set priceDKK = row.dkk %}
{% elseif priceEURO is not empty %}
  {% set priceEURO = row.euro %}
  {# abort - it is here I realized this is some dead-end foolery #}


texts: I would like to import data for fields with multiple locales with the FeedMe plugin. I have to create the JSON feed, so how can I do that? Thanks for your help!


texts: Trying to build params to be able find entries related to an entry and that are related to a specific category

texts:
I want to generate a list of  events that are related to a specific festival and that are related to a specific category. This goal sits alongside some others that are inspiring me to attempt this in a single template and to do so via building params that are then passed to Craft entries tag. Using Craft 3.

First the base params - these return a fine result.

{# Set base criteria for event query #}
{% set params = {
    section : 'events',
    orderBy : 'eventStartDateTime asc',
    relatedTo: [
        { element: entry.id }
    ],
    limit: null
} %}

Next here are the params to try and get the events associated with a specific festival entry and that are related to a specific category.

{# Segment 4 is about categories #}
{% if craft.app.request.getSegment(4) %}
    {# segment 4 is the category slug #}
    {% set cat = craft.app.request.getSegment(4) %}
    {% set relationParam = {
        relatedTo: ['and',
            { targetElement: cat },
            { element: entry.id }
        ]
    }%}

    {% set params = params|merge(relationParam) %}
{% endif %}

What I am seeing in this second scenario is I am not getting results filtered by the category. Feel like I am close but missing something, likely fundamental.


texts:
If I enter a query into the search bar I would like to see an excerpt (let's say 140 characters) of each entry that is related to the query.

Here is what I use on the search result page to display the results.

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

{% if entries|length %}

{{ entries|length }} results:

    {% for entry in entries %}

{{ entry.title }}

    {% endfor %}

{% else %}

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

{% endif %}

How do I add entry excerpts like: https://craftcms.com/search?q=entry


texts: Elements::EVENT_AFTER_SAVE_ELEMENT - Event handler (in module) being called multiple times on creating a single element

texts:
Newbie to Craft CMS. I'm trying to send a push notification to an Android device from a Craft CMS module when an Entry of a particular type (NewsItem) is created / published. Here is the relevant code (which I wrote with the help of StackExchange's very helpful developers):

        // Custom initialization code goes here...
        Craft::$app->elements->on(Elements::EVENT_AFTER_SAVE_ELEMENT, function(ElementEvent $event) {

            // Make sure it's an entry.
            if ($event->element instanceof craft\elements\Entry) {
                $entry = $event->element;
                $entryType = $entry->getType()->handle;

                // Check if it's in the section you care about
                if ($entry->getSection()->handle == 'newsitems' && (($entryType == 'newsitemPhoto') || ($entryType == 'newsitemVideo'))) {
                    // Do your custom logic

                        if($entryType == 'newsitemPhoto')
                            $image_name = $entry->photo->one()->getUrl();
                        else
                            $image_name = 'http://img.youtube.com/vi/' . $entry->youtubeVideoCode . '/0.jpg';

                        $data = array
                        (
                            'title'  => 'News from MY APP',
                            'content' => $entry->title,
                            'imageUrl' => $image_name,
                            'articleId' => $entry->id,
                        );

                       // Code for sending data via push notifications to Android phone

When I create a single entry, I get 4 notifications on my phone instead of one. Here are the debug messages from Android Studio:

D/MyFirebaseMessagingService: onMessageReceived...
D/MyFirebaseMessagingService: sendNotification... Title -> News from MY APP
D/MyFirebaseMessagingService: sendNotification... Content -> null
D/MyFirebaseMessagingService: sendNotification... ImageUrl -> http://img.youtube.com/vi//0.jpg
D/MyFirebaseMessagingService: sendNotification... Article Id -> 147
D/MyFirebaseMessagingService: onMessageReceived...
D/MyFirebaseMessagingService: sendNotification... Title -> News from MY APP
D/MyFirebaseMessagingService: sendNotification... Content -> Test NewsItem
D/MyFirebaseMessagingService: sendNotification... ImageUrl -> http://img.youtube.com/vi//0.jpg
D/MyFirebaseMessagingService: sendNotification... Article Id -> 147
D/MyFirebaseMessagingService: onMessageReceived...
D/MyFirebaseMessagingService: sendNotification... Title -> News from MY APP
D/MyFirebaseMessagingService: sendNotification... Content -> Test NewsItem
D/MyFirebaseMessagingService: sendNotification... ImageUrl -> http://path.to.image/489.jpg
D/MyFirebaseMessagingService: sendNotification... Article Id -> 147
D/MyFirebaseMessagingService: onMessageReceived...
D/MyFirebaseMessagingService: sendNotification... Title -> News from MY APP
D/MyFirebaseMessagingService: sendNotification... Content -> Test NewsItem
D/MyFirebaseMessagingService: sendNotification... ImageUrl -> http://path.to.image/489.jpg
D/MyFirebaseMessagingService: sendNotification... Article Id -> 148

As can be seen, for one entry I created, I get 4 different messages with different data in the fields (even the id is different in the last message). I'm assuming that the event handler in my craft module is getting called 4 times. Is this correct? I would like to debug this in Craft itself, but not sure how to write messages to log file from a module. I tried Craft::info(), but the messages are not showing up in my Craft log files.

Any help would be appreciated. Thanks in advance.


texts: Show dev mode and Yii toolbar on secondary site

texts: I am unclear on how to turn on dev mode as well as the Yii toolbar when viewing a secondary site in Craft.


texts:
I'm having difficulties following the install instructions found at https://docs.craftcms.com/v3/installation.html. I've ssh'd into my server, and I'm running composer to install Craft, as directed in step 1.

Because I've run Composer, the instructions say I can probably safely skip steps 2 and 3. Awesome.

Step 4: Create a database... now wait, when installing Craft via Composer, it gave me the option of running setup from the terminal - which I did. And during this, it asked for database driver, server or IP name, database name, etc. All stuff I needed to know way before I got to step 4.

Step 5. Setup a webserver. Guessing these instructions are specific for local installs? Perhaps this should be made clearer?

Step 6. Run the Setup Wizard. Again... didn't I do this in step one?

After running setup from Step 1, it finished with this:

> save the first user ... done
> save the email settings ... done
*** installed Craft successfully (time: 3.718s)

Looks to me as if everything is as should be. According to the instructions, I should be able to access my new Craft site from my web browser.

Not so much.

I've been having a lot of issues getting Craft 3 to run (if you look at my post history, I've asked like 3 or 4 questions over the last few days related to installation). I don't think I'm that stupid (but I've been proven wrong before!), so I'm not sure why this has been so challenging to me.

Can anyone possibly explain where I'm going wrong?


texts:
We have products with multiple variants (varHeight). The variant information get passed to the cart successfully and order emails. However, they don't show up on the control panel. How can I get the variant information to show up on the order?

Product page

<select name="purchasableId">
<option value="">Select Height</option>
{% for purchasable in product.variants %}
<option {% if purchasable.stock <= 0 and purchasable.hasUnlimitedStock == false %}disabled {% endif %}
value="{{ purchasable.id }}">{{ purchasable.varHeight }} - {{ purchasable.price|commerceCurrency(cart.currency) }}</option>
  {% endfor %}
</select>

Cart page:

  {% if item.purchasable.product.type.hasVariants %}
      {% switch item.purchasable.product.type %}
        {% case "wallpaper" %}
            {{ item.description }}

            Height: {{ item.purchasable.varHeight }}
    {% endswitch %}
    {% else %}
        {#  Non variant purchasable  #}
        {{ item.description }}
    {% endif %}


texts:
Is there a simple way to know if an entry's content changed when it was saved?

I'm pulling data from an XML feed and create/update entries in a section. I need to know which entries has new data. I guess I could check each field value individually, or make some kind of hash and check that. But is there some built-in way in Yii/Craft that is easier?


texts: Why aren't dynamic folders being generated for assets?

texts:
I have a field 'Event Listing Image' set up as:

Field Type: Asset
Restrict uploads to single folder
Upload location [Events]{slug}

There's an asset bucket Events:

Local Folder
File System Path: {fileSystemPath}/content/events/
URL: /content/events/

The field is in a section named Events of type Channel.

The system folder /content/events/ exists and is writable.

If I edit an existing Entry in that channel, I can click upload in that field, but it errors every time with:

  Upload failed for test.jpg. The error message was: ”Error uploading the file: The folder “/Users/matt/Sites/bs_conwyarts/_bespoke/public/content/events/test-event/” does not exist.“

I know it doesn't, it's dynamic based on the entry slug. Why is Craft not creating the folder?

Irony: I have a field called Featured Image set up almost identically on a different Channel that does work:

Featured Image:

Field Type: Asset
Restrict uploads to single folder
Upload location [Artists]{slug}

Asset bucket Artists:

Local folder
File System Path: {fileSystemPath}/content/artists/
URL: /content/artists

UPDATE: looks like a bug. It works fine for new entries posted in the Events channel, it does not work for the existing entry in the Channel. I think I added the field in question after creating the first entry, so it looks like that might be the culprit.


texts: Is there a way to determine if an order requires shipping?

texts:
We're selling a mix of both tangible and digital products with Commerce.

If an order doesn't require shipping, I'd rather just take them to directly to the final one page checkout/payment form.

Is there a way to determine this natively or do I need to add a "RequireShipping" field and loop through the line items to see if one exists in the user's cart?


texts: An unknown error occurred message, only on live server

texts:
Please can anyone give me some pointers.

Just logged into the backend on an older (but live) 3.0.26.1 project. CP is now flashing multiple 'an unknown error occurred' messages on every CP request. Frontend pages are working fine, and my local dev cp version is fine too, no errors there.

I've updated my local dev version to 3.1.28 now, verified no errors and replaced the entire project on the live server but still getting the unknown error messages there.

Web inspector console on live CP is showing various javascript of status 400 codes 'failed to load resource' on things like :

mydomain.com/index.php?p=admin/actions/app/check-for-updates

mydomain.com/index.php?p=admin/actions/dashboard/get-feed-items

mydomain.com/index.php?p=admin/actions/app/get-utilities-badge-count

Also on things like Utilities > Updates the checking spins forever and never gets anywhere. I can't access any of my entries to edit. I've tried disabling all plugins and nuked cpresources folder. Still no luck. Clearing caches through the CP also results in a 400 error in the web inspector.

There's nothing in the db queue table and nothing new turning up in storage/logs or server error log.

Thinking it must be a server config issue but I have no idea on the further debugging process. Could it be folder permission issue?

Craft 3.1.28

PHP 7.2

Update
If I set enableCsrfProtection => false in config/general the errors don't happen and everything is back to normal. Presumably not safe to leave it like this, but what to do to activate again and keep the errors away?


texts: Reorder selection of categories in category fieldtype

texts:
I'm looking to reorder my selected categories within a category field. I'm hoping this is possible because the order an editor selects these categories is important, primarily for the .first() category.

This functionality is currently possible using the entries fieldtype:

But not for the categories fieldtype:

Edit: The order is important here because this field determines where a given piece of content shows up on the site. Our main navigation is defined by these categories.

For instance, if a piece of content is tagged with "Lifelong Health" and "Health Conditions", but the content editor only wants it to show up on the "Lifelong Health" page.

We want an editor to be able to specify multiple categories however, because we have some robust related category action going on, and we have plans on adding in some personalization in a later phase. Having these robust relationships is vital.

In the interim, we've created a second field "Secondary Categories" that an editor can select, and limited the "Category" field to only one selection; but ultimately we'd like to be able to reorder the categories in one field.


texts: How do I modify the entries table to add a new column?

texts:
I've been going through the Craft EntryCount plugin on Mijingo and I've hit a bit of a problem, the way the tutorial shows how to modify the entries table to include the pageviews count doesn't seem to work, I've got the below code in my main plugin file. Does anyone know what the problem is?

public function modifyEntryTableAttributes(&$attributes, $source)
{
    if($this->getSettings()->showCountOnEntryIndex)
    {
        $attributes['count'] = 'Count';
    }
}

public function getEntryTableAttributeHtml(EntryModel $entry, $attribute)
{
    if($this->getSettings()->showCountOnEntryIndex AND $attribute == 'count')
    {
        return craft()->entryCount->getCount($entry->id)->count;
    }

}


texts: Localization - "not found" in CP on language selection

texts:
Folks:

I'm creating a localized site on Craft2 and CraftCommerce. I have followed the instructions for creating a localized site but none of the content shows at the localized URL and the homepage shows the craft default template. The default template has no content.

In the CP, the language is available in the upper right of an entry. The fields that are translatable are labelled. When I click the language, the Craft "not found" page is shown.

My guess is that because no fields exist for the language, no fields can be shown on the front end.

Error from the logs:

2019/02/22 11:28:37 [error] [exception.Craft\HttpException.404] Craft\HttpException in /usr/home/name/temp.domain.com/craft/app/controllers/EntriesController.php:773
Stack trace:
#0 /usr/home/name/temp.domain.com/craft/app/controllers/EntriesController.php(52): Craft\EntriesController->_prepEditEntryVariables(Array)
#1 [internal function]: Craft\EntriesController->actionEditEntry(Array)
#2 /usr/home/name/temp.domain.com/craft/app/framework/web/actions/CAction.php(109): ReflectionMethod->invokeArgs(Object(Craft\EntriesController), Array)
#3 /usr/home/name/temp.domain.com/craft/app/framework/web/actions/CInlineAction.php(47): CAction->runWithParamsInternal(Object(Craft\EntriesController), Object(ReflectionMethod), Array)
#4 /usr/home/name/temp.domain.com/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#5 /usr/home/name/temp.domain.com/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#6 /usr/home/name/temp.domain.com/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#7 /usr/home/name/temp.domain.com/craft/app/framework/web/CWebApplication.php(282): CController->run('editEntry')
#8 /usr/home/name/temp.domain.com/craft/app/framework/web/CWebApplication.php(141): CWebApplication->runController('entries/editEnt...')
#9 /usr/home/name/temp.domain.com/craft/app/etc/web/WebApp.php(291): CWebApplication->processRequest()
#10 /usr/home/name/temp.domain.com/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#11 /usr/home/name/temp.domain.com/craft/app/index.php(73): CApplication->run()
#12 /usr/home/name/temp.domain.com/public_html/index.php(20): require_once('/usr/home/name/...')
#13 {main}
REQUEST_URI=/admin/entries/contact/5-contact/en_gb
HTTP_REFERER=http://temp.domain.com/admin/entries/contact/5-contact

What I've done:

As mentioned, I've followed the instructions in the Craft docs.

I have updated the asset indexes.

I have used environment variables like so:

'temp.domain.com' => array(
        'environmentVariables' => array(
        'devMode' => true,
        'basePath' => '/usr/home/business/temp.domain.com/public_html/',
        'baseUrl'  => 'http://temp.domain.com/',
        ),
        'siteUrl' => array(
        'en_us' => 'http://temp.domain.com/',
        'en_gb' => 'http://temp.domain.com/en_gb',
        )
    ),

I have verified that asset source settings are:

{basePath}images_product/
{baseUrl}images_product/

I have made appropriate fields translatable.

I enabled the locales for each section.

I created and populated subfolders. Index.php looks like so:

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

// Tell Craft to serve the British content
define('CRAFT_LOCALE', 'en_gb');

Additional info:

I am using SEOMatic and that does work as advertised with different meta content showing up for the localized site even if nothing else shows on the page.


texts:
I found this question "404 Page Not Showing" asked 3 years ago that the person who asked figured it out but didn't really expand on how they did.

I have basically the same issue, craft doesn't load the 404 error ever, it simply loads the template with nothing.
https://footwearoutfitters.net/123

I haven't edited any .htaccess files

Routes is left unmodified, both in the CP and the file itself.

I'm wondering if I setup my entries incorrectly for the URI, anyone have ideas or think of somewhere else I could give info on to help this along?

Here is my .htaccess folder in the public

<IfModule mod_rewrite.c>
  RewriteEngine On

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


texts: Count number of consecutive years in category array

texts:
I need to count the number of consecutive years a user has been a member of our organization. For example, if they've been a member from in 2018, 2019, 2020 and 2021, their loyalty will be 4 years.
If they've been a member in 2018, 2019 and 2021, their loyalty will be 1 year (they missed 2020.)
I'm currently using Categories to assign a year to Users in Craft to do the assignment of a year to a person.
Hope that makes sense. I would very much appreciate some help on how to tackle it!


texts: Passing Multiple Relation Criteria In Plugin

texts:
I have a channel (projects) that has two different entries fields (year & research theme), both of which I want to be able to search in a plugin.

The docs for the relatedTo entries method show under the heading "Passing Multiple Relation Criteria" that it's possible to do this within twig, however I'm not sure how to do this in my plugin using php. Obviously the below won't work:

# Find all projects that match the supplied year and research theme.
$projectCriterea = craft()->elements->getCriteria(ElementType::Entry);
$projectCriterea->section = 'projects';

# Something like this?
$projectCriterea->customField1->relatedTo = $yearEntryModel;
$projectCriterea->customField2->relatedTo = $researchThemeEntryModel;

$projects = $projectCriterea->find();

Any help would be amazing. Thanks.


texts: Content creation and translation workflow

texts:
I've developed my Craft website locally ( in fact on a virtual machine on the company intranet, so it's accessible within the company ).
Now it's time to fill the site with contents and translate them for 7 different locales.

My boss is asking me to provide a CSV or similar structured file to let other employees and a translation agency fill the content without accessing the CMS directly.
Is this possible? Is it a good approach?
Keep in mind that the entries have some Matrix field.

Also, is it better to insert the content in the staging environment or in  developement? Or it doesn't matter?


texts: How do I access the properties of an object which triggered an event?

texts:
I'm trying my first plug-in; it's to automatically create an entry in a section when a user belonging to a specific user group is activated. However I'm not that hot at PHP and I can't figure out how I would check that the user being activated belongs to a given user group. Here's my basic code from in the main plugin file's init() function:

public function init() {
    craft()->on('users.onActivateUser', function(Event $event) {
        // check the user being activated belongs to the user group 'artist'
        // ???

        // now save an entry on their behalf
        $entry = new EntryModel();
        ...

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

        if (!$success)
        {
            Craft::log('Couldn’t save the entry "'.$entry->title.'"', LogLevel::Error);
        }
    }
}


texts: Variable "entry" does not exist - error on homepage single entry

texts:
Relatively new to CraftCMS and getting Twig error "Variable "entry" does not exist" on my home page.
Noticed another post said to leave URI blank which should fix but didn't.
Just looking to output something very simple i.e. {{ entry.featureHeading }}
Appears to not be recognising the home page as an entry but it is and is setup as a 'single'


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

I have set the following in general.php:

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

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

Oops!

Invalid verification code. Please login or reset your password.

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

Cole


texts:
Craft looks VERY promising to me! Still try to figure out if it could be perfect for our new project, though.

Can those requirements be fulfilled by craft?

Is there an image gallery module where i can define captions? means small (copyright)text under the thumbnails and also under the enlarged images (say, in a modal)?
Can I define a folder full of images and tell Craft to use this as the source for my gallery, so it automatically generates the gallery for me? An image description (or alt text etc.) should automatically be used and displayed as captions.

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

Thanks a lot for your help and greetings!


texts: Getting metadata/column names for empty resultset

texts:
I have a dynamically generated sql. How can I know what the column names are, even if the database returns an empty result?

$sql = "select t.bar, count(o.foo) as amount
        from craft_table t join craft_otherTable o on t.id = o.id";
$resultset = craft()->db->createCommand($sql)->queryAll(true);

In Java, i can do something like this:

for(int i=0;i<resultset.getMetaData().getColumnCount();i++){
    columnNames.add(resultset.getMetaData().getColumnLabel(i))
}

I am looking for a similar solution in PHP.

I have tried this:

$command = craft()->db->createCommand($sql);
$command->prepare();
var_dump($command->getPdoStatement()->getColumnMeta(0));

...but the output is bool(false). I feel like I am missing something.


texts: In a template: Is there a way to call the parent's folder name?

texts:
For Structured entries, I always have about the same folder structure.
If I could access the parent's folder name, I woudn't have to change the {% includes %} when copying a folder.

e.g.:

blog
---_common
---_entry
---_listing
---index

so _entry looks like this:

{% extends "_layouts/_layout" %}

{% block content %}
    {% include "blog/_common" %}
{% endblock %}

and _listing looks like this:

{% set params = { section:'blog', limit: gl_config.cf_blog_limit} %}
{% paginate craft.entries(params) as entries %}

    {% for entry in entries %}
        {% include "blog/_common" %}
    {% endfor %}

    {% include "_includes/_pagination" %}

{% endpaginate %}

They look almost the same for every structure channel I use (e.g. discography, pressreleases, projects etc etc.)

If I could use {% include "PARENT_FOLDER_NAME/_common" %}

I could just duplicate the folder and don't have to worry about these templates!

btw: the _common template looks about like this:

             {{ entry.postDate | date("d") }}
             {{ entry.postDate|date("F Y") }}

{{ entry.title }}

            {% set tags = entry.cf_blog_tags %}

            {% if tags | length %}
                {% for tag in tags %}
                    {{ tag.name }}
                {% endfor %}
            {% endif %}

        {#
            Content Matrix text / images / files / quotes / slideshows / videos etc..
        #}
        {% include "_includes/_content_blocks" %}

Permalink

        {# Edit #}
        {% include "_includes/_edit" %}


texts: How do I find live and pending entries when using an array?

texts:
I have this in my listings template, but the 'pending' parameter does not seem to work.

{% set urlCat = craft.request.getSegment(3) %}
{% set category = craft.categories.slug( urlCat ) %}
{% set allEntries =  craft.entries.status('live, pending').section('sectionName').relatedTo(category).find() %}

This seems to only return 'live' entries even though I do have 'pending' specified.  I've tried this several ways and cannot seem to make it work.

The strange thing is that this seems to work fine on my single entry page where I have:

{% set entry = craft.entries.section('sectionName').slug(selected).status("live, pending").first() %}

Any ideas?  Thanks :)


texts:
I’m using the Digital Products plugin to sell licenses so that users are listed on the site for a certain amount of time.

The options are something like "buy 3 month", "buy 6 month" etc. You see, the concept of the cart doesn’t really apply here. There would be no point in buying "3 month" twice.

That’s why I’d like to set the items in the cart always to the quantity of 1. Even better would be if I could empty the cart each time a product is added to the cart. That’s because people are supposed to select between the given options, not buying several options at once or multiple times.

Any hints?


texts: Use Assets to create transformations of external images

texts:
Can I somehow use Asset transformations on external images (having them cached on my server)?

Let's say I have this image on "http://www.example-external-website.com/image.jpg" and I wan't to pull this image into my own server and create a small 100x100 thumbnail.

Is this possible?


texts: Iterate through all entries and count a specific value

texts:
I am having entries in a Craft channel-section. Each entry has the field "type" with one category filled. I need to iterate through the entries and count the amount of each category.

Example:

Entry 1, Category: One
Entry 2, Category: One
Entry 3, Category: Two

Produces something like

One: 2, Two: 1

So I know which category is used how often. In any language I would use a key/value set and just increment the amount each time I find the specific category, but that seems to be impossible with Twig in Craft.

How can I achieve that?


texts: Cannot grant user group plugin permission without hasCpSection

texts:
A user group cannot be given access to a plugin without the plugin having hasCpSection.

I don't want to give anonymous access to the plugin's methods; is there not an option to have a plugin listed for user group permission allocation without it having an cp tab? Too many cp tabs cause a JS error - but that's another issue...