texts:
I've got a navigation bar that displays different links for logged in users using {% if currentUser %}. However, when clicking through links, sometimes it won't pick up that someone is logged in.

The same issue crops up occasionally with "denied permissions" error pages. Again, reloading the page will pick up the user session and display the template normally.

It's inconsistent which pages (and servers) it happens on. I'm not using any {% cache %} tags in the twig templates either.

Is there a cp setting or config/general.php option I'm missing?

Edit: Looks like the autogenerated appId based on filepath must have been the issue.


texts:
I replicated what was mentioned here: (Plugins: Managing Related Records)

However I'm not seeing any new table created to on plugin install.

I have a "LeaderRecord" with

'trips'     => [static::MANY_MANY, 'pluginexample_TripRecord', 'pluginexample_trip_leaders(tripId, leaderId)']

with the same relation defined in a "TripRecord", am I missing something to have the tabled created?

Thanks!


texts: How to use alterColumn to change the values of an ENUM field in a DB Migration

texts:
I need to add a value to my plugin database for an ENUM field but I am struggling to find the correct syntax for the alterColumn method.

I want to do this but with alterColumn if possible?

ALTER TABLE tableName CHANGE columnName columnName ENUM('existingOption1', 'existingOption2', 'newOption') DEFAULT NULL;

Cheers


texts:
On various Craft sites, I've needed to provide my clients with access to certain variables used across the site. Things like open hours, specific seasonal color palettes, on / off operation toggles. In the past I have made a Static page that has a single table field with name and value pairs. I have then retrieved these values at the start of my layout template and output them on various pages as needed.

1) Is this this best way to do this?

2) Related question (and more pressing): For a recent project, I have been unable to grab the variables as I've done in the past. Not sure why...

{% set theRows = craft.entries.section('theSection').one() %}
{% set siteVariables = [] %}
{% for row in theRows %}
  {% set siteVariables = siteVariables | merge({ (row.name): row.value}) %}
{% endfor %}

My section entry query is coming up blank and dumping siteVariables causes a server error.  The set up seems the same as a working installation. Am I missing something? craft.entries.sectionId(ID).one() also doesn't see to work...


texts: Update multiple database entries via controller

texts:
I've inherited a Craft site that is a mix of a custom plugin (the main site) plus a Laravel Dingo plugin (behind which the bulk of the data in the db lives), plus Solr, and I'm trying to untangle it.

I want to add a function to my controller that updates multiple entries in the database but I can't figure it out. I'll post a snippet of a working existing code along with my attempt:

//Controller
==working, existing code===
public function actionUpdateGuide() {
    $this->requirePostRequest();

    $attr = craft()->request->getPost('guide');
    $request = craft()->MyPlugin_guide->updateGuide($attr);

    if ($request && $request->isSuccessful()) {
        $this->clearCachedAsset($attr['id'], 'guide');
        $this->redirectToPostedUrl();
    } else {
        $this->hydrateInvalidForm($request, $attr);
    }
}

==not-working, my function===
public function actionPositionGuide() {
    $this->requirePostRequest();

    $attr = json_decode(craft()->request->getPost('guide.json'), true);
    $neworder = array();

    foreach($attr as $row) {
        $guide = array(
            'id' => $row['name'],
            'position' => $row['value']
        );

        array_push($neworder, $guide);
    }

    $request = craft()->MyPlugin_guide->positionGuides($neworder);

Then

//Service
==working, existing code===
public function getGuideLocations($id, $page) {
    $url = $this->getUrl() . "/" . $id . "/locations?page=$page";
    $response = craft()->laravel_plugin->send('get', $url);

    if (!$response->isSuccessful()) {
        return array("error" => $response->getStatusCode(), "msg" => "get_guide_locations_error");
    }

    return $response->json();
}

==non-working, my function==
public function positionGuides($attr) {

    foreach($attr as $guide) {
        craft()->laravel_plugin->update($attr);
    }
}

I'm confused because I assumed the normal workflow was controller->service->model->database, but this seems to be controller->service->anotherplugin-service.

Looking in the controller for this Laravel plugin, I see:

public function update($id) {
    $guide = Guide::find($id);

    if (is_null($guide)) {
        return 'error';
    }

    $locations = Input::get("locations", array());
    if(!empty($locations)) {
        $locations =  Location::whereIn('id', $locations)->lists('id');
    }

    $guide->locations()->sync($locations);

    $guide = $guide->fill(Input::all());

    if (!Input::has('image_id')) {
        $guide->image_id = null;
    }

    return $guide->save() ? $guide : $guide->getErrors();
}

And here is the laravel_api model for it:

protected $table = "guides";
protected $fillable = ["name", "city", "type", "image_id", "description", "status", "updated_by", "document", "position"];
protected $dates = ['deleted_at'];
protected $rules = ["name" => "required"];
protected $appends = array('location_detail');

protected $searchable = ['name', 'description', 'subtitle'];

public function locations()
{
    return $this->belongsToMany('Location');
}

Any advice would be appreciated.


texts: Display an entry's level 1 categories only if the entry is not related to any of that category's children

texts:
I'm struggling with how to do this in Twig... I feel like it would be easier in a full programming language.

If an entry's categories look like this:

A
    - A1
    - A2
B
C
    - C1

I need to output a list like this:

A > A1
A > A2
B
C > C1

I can't seem to figure out how to avoid printing all the top-level categories on their own. This is what I've managed to output:

A
A > A1
A > A2
B
C
C > C1

I have a feeling I'm going to feel dumb when someone answers this, but any help is appreciated.

Edit: I've found a solution.

Before listing the categories, I run a for loop on just the entry's level 2 categories and collect their parents' IDs using an empty array and the merge filter. Then, when listing the categories, I put a conditional so that level 1 categories are not listed if their ID is in the array.

It seems an awkward way to do it, and I'm still interested in better solutions.


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

texts:
This issue becomes especially difficult when there are multiple environments, with multiple developers working on different features that affect the data structure.

The holy grail is a git-style distributed database setup, and I believe the Craft team is working on a solution that integrates with Craft Core. But it'd be great to hear how the community is handling this currently.


texts: Uploading Assets - PNG changed from 72 dpi to 96

texts:
I've seen a couple strange things that Craft does when uploading images (like upsizing jpgs). The most recent, every time I upload a .png file it changes it's DPI from 72 to 96 for some unknown reason (why is this not in the documentation?) and it doesn't alert the user that it's doing so.

1) why?
2) why is this not spelled out clearly in the documentation?
3) Shouldn't Craft alert the user that it's altering your image so you don't spend hours trying to figure out what happened to your carefully planned images?
4) how can I stop this from happening?


texts:
I'm a bit confused by the way that Craft now handles Matrix blocks. I've read the documentation a few times and I'm still not sure if I have it.

Here's what I have:

{% set myMatrixBlockQuery = craft.matrixBlocks().ownerId(4).type('block__artists') %}
{% set matrixBlocks = myMatrixBlockQuery.all() %}
{% for block in matrixBlocks %}
  <li>{{ block.id }} / {{ block.artistName }}</li>
{% endfor %}

But all that gets output is:

8 /
9 /
10 /

Where 10 (etc) is the ID of the block. It's not outputting the artistName despite that field existing and having content. Is my query wrong?


texts:
I have this simple element model and I'm trying to add dynamic class within loop.
So every time a model outputs, It outputs dynamic class. Can't go for another loop within loop, in case I could, therefor It'd be easy.

            {% set tags = slide.foodTags %}
            {% if tags %}

            <div>
                  {% for tag in tags %}
                        <span class="{# dynamic-class #}">
                            {{ tag.title }}
                        </span>
                  {% endfor %}
            </div>

           {% endif %}


texts: Tag Localization: how to create a tag without translation fallback version?

texts:
I'm dealing with tag localization on an English/Spanish site and have figured out that if I create a new tag, both En and Es elements are created by default, which would be O.K. if I never had to filter tags for locale.

I discovered that if I manually delete the duplicate element from the other locale, they do only show in their respective locales, which is ideal for this. Is there a way to do this via the admin UI?

I have made the tags field on my entries non-translatable, but what would stop Craft from creating duplicate elements for the other locale?

EDIT: Also, if I update a tag, the other locale version that I deleted is recreated automatically :/


texts:
I've moved from Wordsmith to Typogrify because of the additional config options, which are great. I am having an issue though with line breaks appearing in  tags in Chrome in very specific cases. I have hyphenation turned off.
Link here:
https://thecinematheque.ca/films/2021/film-about-a-father-who
Break added after "Film About a Father Who" when window is around 720px wide. No idea if this is a CSS issue but I cant see anything that would cause that.
I do see a &#8203; element added near by. Not sure where that is coming from.


texts: Override entry.url / entry.getUrl() Method

texts:
For certain entries I would like to be able to override how Craft generates the URLs to them.
So I create an Entry Model in my module extending from \craft\elements\Entry and override the getUrl() method there.
However I did not manage to replace Craft's class with mine.
How can I achieve this? I found solutions like Yii::$container->set('craft\elements\Entry', '\modules\Entry'); or the same with Craft::
I placed it in my index.php, I tried it in the head of /config/app.php, but nothing happened.
Any suggestions?


texts: Is there a way to get categories relating to a specific entry within a plugin?

texts:
When I get an Entry Object that has been set, I notice all of my fields except the Category fields are available to me. For example:

[_behaviors:yii\base\Component:private] => Array
    (
        [customFields] => craft\behaviors\ContentBehavior Object
            (
                [adjustedRemainingLife] => 100%
                [adjustedRemainingYears] => 116
                [answerSets] => [{"col3":"Paving and curbs are less than 3 years old, and in good condition. No repairs are needed, preventative maintenance ","col1":"Paving and curbs are in good condition, and only require routine maintenance - 90%","col2":"Minor repairs and patching are required, not exceeding 30% of value -\r\n60%","col4":"Significant repairs are needed to as much as 60% of value. - 30%","col5":"All or majority of systems should be replaced - 0%"}]
                [groundsQuestions] =>

Where groundsQuestions is my category field, I figure if it isn't flowing through, there must be some way to get that value in a plugin?


texts: Missing buttons in settings after update to 2.5 beta

texts:
After updating my dev install to 2.5 beta, I seem to be missing the action buttons for each tool category in the settings page, see attached image.

Anyone else experienced this?

This applies to all 5 categories ("update asset indexes", "clear caches" etc)

I tried to re-install the app folder (by completely replacing, not merging) but with no luck, so I'm beginning to think that this all comes down to some database issue...


texts: ElementAPI - Can I use javascript/ajax to load json

texts:
Probably a dumb question, but since i wasn't sure while reading on github, i'll ask here.

I am wondering if I can reach the JSON I created with an URL or is it only for use in PHP?

I would like to load entries from craft from a json with ajax when i click on a button and i wasn't sure if it was possible with this plugin since there is no exemple.

Anybody can help me?

Thanks!


texts: Will a change to verificationCodeDuration be updated retrospectively?

texts:
I've amended the time people have to verify an account, using:

'verificationCodeDuration' => 'P7D',

But, I've done this retrospectively, after the verification emails have all gone out (quite a lot of them). Will this new verification time be applied to verification links that have already been sent out? Or will I need to get those emails sent again, as only new verification links will have this applied?


texts: Is there a way to reduce the search index?

texts:
Our search index table (craft_searchindex) is over 500,000 rows and it takes a few hours to index. We have 11 languages, and each is being fully indexed. It takes a few hours to complete.

Are there any ways we can reduce the search index size (e.g. only one language, or specific sections?


texts: How can I add data to a matrix field from a module without overwriting existing data?

texts:
I have an entry that has a matrix field. From a controller in a module I want to add additional data to it (e.g. some text that I have in a variable $messageText) but without overwriting the existing blocks.
So far I have in my controller:
public function actionPostMessage() {
        $this->requirePostRequest();
        $request = new \craft\web\Request;

        // this is the text (from a POST request) that I want to
        // add to the matrix field
        $messageText = $request->post('messageText');

        $entryId = $request->post('applicationId');
        $currentUser = Craft::$app->getUser()->getId();

        // I can get the entry all right:
        $entry = Entry::find()
            ->id($entryId)
            ->section('applications')
            ->authorId($user)
            ->one();

        // and this is the matrix query object where I want to add the
        // $messageText received from a post request
        $messages = $entry->messages;
...

I can loop through $messages and get the existing messages without problems:
        foreach ($messages as $message) {
            $temp = $message->messageText;
        }

But how can I append the new text from the $messageText variable to it without overwriting the existing data already in the matrix field?

EDIT: I found this info on Github: Creating / editing single matrix blocks on the front end #5717 and based on that info I have added the following code:
        $sortOrder = (clone $entry->messages)->anyStatus()->ids();
        $sortOrder[] = 'new:1';

        $newBlock = [
            'type' => 'textMessage',
            'fields' => [
                'messageText' => $messageText,
                'outgoing'    => true,
                'messageRead' => false,
            ],
        ];

        $entry->setFieldValue('messages', [
            'sortOrder' => $sortOrder,
            'blocks' => [
                'new:1' => $newBlock,
            ],
        ]);

        try {
            $success = Craft::$app->elements->saveElement($entry);
        } catch (ElementNotFoundException $e) {
            echo $e;
            echo 'Element not found.';
        } catch (Exception $e) {
            echo $e;
            echo 'Element not saved';
        }

It does not throw any errors and $success is true, but nothing is updated in the DB/new message does not appear there.
Any ideas what may be missing here? Why it is not saving the new block in the matrix field?


texts: How to UNION Craft blog articles array with Social Media plugin (non craft table)

texts:
I'm looking for a way to merge blog article entries with social media entries (non craft table). The idea is to output both entry types together from the same array, this will allow me to order all entries by date.

The social media plugin that I have put together queries the non-craft social media table but I need a solution to UNION the two tables together.

How would I go about doing this within Craft?

My table structure for craft_archived_social_items

id int
unique_id varchar(255) NOT NULL,
account varchar(255) NOT NULL,
category varchar(255) NOT NULL,
title text NOT NULL,
content text NOT NULL,
image varchar(255) NOT NULL,
link text NOT NULL,
date datetime NOT NULL,
status varchar(255) NOT NULL DEFAULT 'inactive',
date_cached datetime NOT NULL,

PRIMARY KEY (id)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

My service file is currently using the db->createCommand to query the table

    $social_items = craft()->db->createCommand()
        ->select('title, content, date, category, id, account, unique_id, image, link')
        ->from('archived_social_items')
        ->offset($offset)
        ->limit($counter)
        ->order('date desc')
        ->queryAll();


texts:
Searching for a way to add products to cart and sending the csrf token  with ajax
This is my current code;
$('.add-to-cart-form').on('submit', function(e) {

            e.preventDefault()
            var formData = new FormData($('.add-to-cart-form')[0]);
            formData.append('action', 'commerce/cart/update-cart');

            $.ajax({
                contentType: false,
                processData: false,
                type: 'POST',
                url: '',
                dataType: 'json',
                data: formData,
                success: function(response) {
                    var cartCount = response.cart.totalQty;
                    $('.cart-count').text(cartCount);
                    if (response.success) {
                        console.log('success');
                        console.log(response.success);
                    }
                    else {
                        console.log('error');
                        console.log(response.success);
                    }
                }
            });
        });


texts:
I've tried following the guide for setting up multiple sites (https://docs.craftcms.com/v3/sites.html#creating-a-site) but I think i'm missing something.

Firstly the craft install on your beta site, does it share the same database?

Secondly I'm not exactly sure what 'step 7' is asking me to do, could you please explain?

FYI, I'm using plesk on my hosting.

Thanks in advance


texts: Create a Structure page with entries list

texts:
I have created a Structure page 'Products' with a URL of '/products' so that I can write a description etc, but then I would also like to pull in the Products into the template. I'm a little unsure on how best to achieve this.

The Sections are created as follows;

Page
Handle: page
Type: Structure
URL Format: {slug}
Entry Template: page/_entry

Product
Handle: product
Type: Channel
URL Format: products/{slug}
Entry Template: products/_product

In ExpressionEngine I would have pulled in a Channel entries tag for the page and then another entries tag for the products.


texts: onBeforeRender event? Is there an event or hook I can use with my plugin?

texts:
I am looking for away to manipulate and record data about an entry before it is returned to the client. I could do this with AJAX after the page is rendered by the browser but I would prefer to do this on the server.

Is there an event or hook I can use to accomplish this?


texts: Why would one environment use "+" instead of "%20" for spaces when using url_encode filter?

texts:
I just uploaded some templates to the server and discovered that some of my url encoded strings are being output with a "+" for spaces instead of the "%20" that is desired. It is fine in my local environment. Any ideas?

According to the twig encode_url documentation url_encode now uses php's rawurlencode by default:

  Internally, Twig uses the PHP urlencode (or rawurlencode if you pass true as the first parameter) or the http_build_query function. Note that as of Twig 1.16.0, urlencode always uses rawurlencode (the raw argument was removed.)

I have also tried passing 'true' as the first parameter just in case. No luck.


texts:
Have used the pretty neat Import and Export plugins from Bob Olde Hamsink.

But, those two do not handle Matrix data.

The question is basically:

What is the 'most common way' to import and export data to/from Matrix fields in Craft CMS.


texts: How to automatically rename image uploads?

texts:
How to automatically rename the image files to a random string during the upload process? For example, I have an image named "big_poster.jpg" and I want it to be saved as something random, for example "2680542675157_cc7m541v_l.jpg"

I see every asset have a "Filename" and "Title" field. Would be possible to use these fields to generate a random string? Perhaps using the Randomm plugin?


texts: 404 on all pages but home after switch to https

texts:
I have an SSL certificate installed on the server. Now I want to switch to https:// instead of http:// as the site is showing as "not secure".

I've updated the siteUrl and baseUrl in config/general.php:

  ),
  'www.website.com.au' => array(
    'devMode' => false,
    'siteCached' => true,
    'omitScriptNameInUrls' => true,
    'allowAutoUpdates' => false,
    'siteUrl' => 'https://www.website.com.au/',
    'environmentVariables' => array(
      'baseUrl' => 'https://www.website.com.au/',
    ),
  ),

That didn't do anything.

Then, I tried updating these rules in the .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]
</IfModule>

updated to:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]
</IfModule>

and

<IfModule mod_rewrite.c>
    RewriteEngine On

  RewriteCond %{HTTP_HOST} !^www\.
  RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

  RewriteCond %{HTTP_HOST}%{REQUEST_URI} www.website.com.au/home$
  RewriteRule ^(.*)$ http://www.website.com.au [R=301,NC,L]

  RewriteCond %{HTTP_HOST}%{REQUEST_URI} www.website.com.au/about-us$
  RewriteRule ^(.*)$ http://www.website.com.au/about-us/our-story [R=301,NC,L]

...

updated to:

<IfModule mod_rewrite.c>
    RewriteEngine On

  RewriteCond %{HTTP_HOST} !^www\.
  RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

  RewriteCond %{HTTP_HOST}%{REQUEST_URI} www.website.com.au/home$
  RewriteRule ^(.*)$ https://www.website.com.au [R=301,NC,L]

  RewriteCond %{HTTP_HOST}%{REQUEST_URI} www.website.com.au/about-us$
  RewriteRule ^(.*)$ https://www.website.com.au/about-us/our-story [R=301,NC,L]

...

These updates to .htaccess work for the home page, but when I visit any other page, the URL is https, but the page displays a 404 Not Found error.

How do I switch to https properly?

Thanks


texts: Where can I set how the pagination links render?

texts:
I have inherited a Craft 3 project in which the pagination links render with a query parameter "page": https://mysite.com/blog/?page=2 but this makes crawlers like HREFS to ignore the Next and Prev links (resulting in over 100 "orphan" pages).
Where can I reset my pagination links to the standard https://mysite.com/blog/p2 format?


texts:
I'm working on a website that was developed by someone else before me, I added a new section and template, I uploaded all my files, created my new section and field and created my first entry everything was looking good, I decided to add a second entry to ensure that everything is working, but when I preview the entry Craft is showing both entries on one page instead of creating separate page for the entries. Please, can someone tell what is the reason for that I'm new using Craft below is the code that I wrote for the new template?

{% extends "layout/_layout" %}

{% block breadcrumbs %}
    {% include 'includes/_Breadcrumbs' with { 'currentTitle' : entry.title } %}
{% endblock %}

{% block content %}

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

        {% include 'includes/_pageTitle' %}

        {# Top Content Section 1 #}

                        {% for block in entry.Headline %}

                                {{ block.headline }}

                            {% if block.subHeadline %}

{{ block.subHeadline }}

                            {% endif %}
                        {% endfor %}
                        {% if entry.leadInText %}
                            {{ entry.leadInText }}
                        {% endif %}

                        {% include 'includes/_asideBox' %}

        {# Start Sections 2 - 5 #}
        {% for block in entry.newContentMatrix %}
            {% switch block.type %}

                {% case "twoColumnSection" %}
                    {% include 'includes/_sectionTwo' %}

                {# Section 3 #}
                {% case "paragraphSection" %}
                    {% include 'includes/_paragraphSection' %}

                {# Double list Section #}
                {% case "listSection" %}
                    {% include 'includes/_listSection' %}

                {# Section 4 #}
                {% case "miniFormSection" %}
                    {% include 'includes/_miniFormSection' %}

                {# Call to action Banner #}
                {% case "callToActionBanner" %}
                    {% include 'includes/_callToAction' %}

            {% endswitch %}
        {% endfor %}

    {% endfor %}

    {% includeJsFile "/public/ui/js/accodion-menu.js" %}
    {% includeJsFile "/public/ui/js/SideNavTrigger.Js" %}

{% endblock %}


texts: Image Optimize: How do I access specific colors?

texts:
In the Image Optimize plugin, we have access to the color palette, however it's not clear in the documentation how to access specific colors (https://nystudio107.com/docs/image-optimize/AdvancedUsage.html#color-palette). This works:

{% set optimizedImages = entry.myAssetField.one().optimizedImagesField %}
{% for color in optimizedImages.colorPalette %}
    <div style="background-color: {{ color }}">
    </div>
{% endfor %}

But it returns this which is obviously not a valid CSS background-color:

#06070d
#e0e5e8
#2d539d
#5e92b9
#848484

Which I assume is an array, but I'm not quite sure access each color individually?

Also, it would be nice to know how the order is determined? Light to dark, dark to light? I'm interested in building a background gradient from two colors that match the image.

EDIT: I just noticed that the documentation says, "These colors are sorted by color dominance, and can be used to style other HTML elements with complimentary colors." So, is there a way to choose the 1st and 2nd most dominant colors?


texts: Templating basics: extend, include or use?

texts:
I'm making first steps with Twig in Craft. Ok, it's a Twig question. But maybe you can give me the best practice for Craft?

I'm used to create templates Top-Down, like having a master.html template that includes footer.html, header.html, content.html etc.

Now Twig and with this Craft suggests I'd rather extend / inherit parent templates.

It looks like the easy way to start if I simply use {% include "pages/partials/_head.html" %} – but will this later on, when I start working on the content, somehow prohibit accessing the unique features of extend?

So: Should I grasp the logic of extend first or doesn't it matter?


texts: Double escaping Regular Expressions in Craft's Twig replace filter?

texts:
Just trying to use Craft's Twig replace filter to remove number prefixes from the beginning of User Groups names and I have had to double escape the character classes etc to get it to work. I tried this...

{{ group.name|replace('/^\d+\.\s/','') }}{% if not loop.last %}, {% endif %}

and it didn't work so for some reason I tried this...

{{ group.name|replace('/^\\d+\\.\\s/','') }}{% if not loop.last %}, {% endif %}

...and it worked. Is there a sensible explanation for this as Regular Expressions are like Voodoo?!


texts: How can I get the cart total item? I tried using a “length” filter but it’s not working with that

texts: I am using the craft commerce plugin and I want to fetch total qty of the cart items. I have tried the length filter but its not working. Is there any other filter that can help in it?


texts:
I'm trying to make a very basic plugin that will send an email alert to a User if an Admin changes their User Group.

I thought I could use the onBeforeSaveUser to get the User's current User Group, and then use the onSaveUser event to compare that with the Event's User Group - and then if they differ, do the mail sending.

It doesn't work, and I don't know why. Both events always get the same value for the User Group. What am I not understanding correctly?

private $existingGroups = NULL;

public function init()
{
    craft()->on('users.onBeforeSaveUser', function(Event $event) {
        $eventUser = $event->params['user']; // get the user we are editing

        $user = craft()->users->getUserById($eventUser->id); // get that user's existing information, before we edit it

        $this->existingGroups = $user->getGroups(); // store the groups the User belongs to
        GroupNotificationPlugin::log("existingGroup: " . $this->existingGroups[0]->name, LogLevel::Info);
    });

    craft()->on('users.onSaveUser', function(Event $event) {
        $user = $event->params['user']; // get the user we are editing

        GroupNotificationPlugin::log("Was: " . $this->existingGroups[0]->name, LogLevel::Info);
        GroupNotificationPlugin::log("Now: " . $user->getGroups()[0]->name, LogLevel::Info);

        if($this->existingGroups[0]->name != $user->getGroups()[0]->name){
            GroupNotificationPlugin::log("Changing group", LogLevel::Info);
        }
    });
}

Was: XXX and Now: XXX are always reporting the same, even when I know that I have changed the User Group (unchecking the old one, checking a new one, saving).


texts:
How to remove the date behind a asset filename or prevent add a date behind the filename? I'll have a plugin that's modifies an existing pdf with SETA SIGN. To do so I'm copy the current asset, modify it in the temp folder, unlink original, copy modified file and unlink the temp file. I tried to rename the file (with $rename) but still the date is added behind the filename. I'll found something with avoidFilenameConflicts but as far as I'll see this is for new assets not for moving or renaming assets.
$assetFilePath = $asset->getVolume()->getRootPath() . DIRECTORY_SEPARATOR . $asset->getPath();
....
        unlink($assetFilePath);
        copy($tempPath . DIRECTORY_SEPARATOR . $asset->filename, $assetFilePath);
        unlink($tempPath . DIRECTORY_SEPARATOR . $asset->filename);

...
$newFileName = 'bla.pdf';
$rename = Craft::$app->assets->moveAsset($asset,$asset->getFolder(),$newFileName);

bla.pdf becomes bla_2021-03-26-124307.pdf but I'll want just 'bla.pdf'.


texts:
I'm a bit confused about the usage of these two. Let's say I want to create a new entry from a controller. For me, the nicer option would be to user something like this:

$entry = new EntryModel();
$entry->sectionId = 4;
$entry->typeId = 4;

$entry->setContent([
    'foo' => 'bar',
    'xyz' => '456',
]);

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

Somehow this is not working for me. Instead, I have to use the uglier version like this:

$entry = new EntryModel();
$entry->sectionId = 4;
$entry->typeId = 4;

$entry->getContent()->foo = 'bar';
$entry->getContent()->xyz = '123';

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

Any ideas why the first example might be failing? Especially when working with more than two attributes, the first example would be way more easy to handle.


texts: Encoding special characters even with the raw filter due to include

texts:
Hey guys i have something odd happening and I don't understand why:

The opening of my template i set a variable {% set text = component.textarea ?? null %}

Lower in my template i have the following: {% set text = include('_components/_dataTypes/textarea') %}

That template only currently has {{ text }} in it so as of right now doesn't mean much.

Then last in my template i have {{ text|raw }}

However characters are still encoded.

I've found that if i remove the include template, even though all it includes is {{ text }} that |raw works. I should note that if i put |raw in the include template, it still does not work.

Why is that? Is it a parse order thing or what's going on there that causes the include to ignore the filter? I should note that using Wordsmith and the |pde filter does work regardless of the include... however characters such as < > ' " etc. are still encoded, where as they are not without the include.

Please help me understand why this is occurring. Thank you.


texts:
I'm getting an error message when trying to back up the Craft DB.

2019-09-04 10:21:09 [-][1][6eba342acf082a62ea47300d68faddf4][error][yii\base\Exception] yii\base\Exception: Could not create backup: The shell command "mysqldump --defaults-extra-file="/var/www/html/storage/runtime/temp/my.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --set-charset --triggers --single-transaction --no-data --result-file="/var/www/html/storage/backups/client-name_190904_172109_fnrhjpwxac_v3.2.10.sql" craft && mysqldump --defaults-extra-file="/var/www/html/storage/runtime/temp/my.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --set-charset --triggers --no-create-info --ignore-table=craft.assetindexdata --ignore-table=craft.assettransformindex --ignore-table=craft.sessions --ignore-table=craft.templatecaches --ignore-table=craft.templatecachequeries --ignore-table=craft.templatecacheelements --ignore-table=craft.cache --ignore-table=craft.templatecachecriteria craft >> "/var/www/html/storage/backups/client-name_190904_172109_fnrhjpwxac_v3.2.10.sql"" failed with exit code 127: sh: 1: mysqldump: not found in /var/www/html/vendor/craftcms/cms/src/controllers/UtilitiesController.php:343

I'm not sure where to look to solve this. How may I get the DB to back up?


texts: Add Checkbox to adminpanel / form settings

texts:
I use the plugin freeform and now i need a checkbox/lightswitch/selectbox where i can select a specific behaviour (custom variable/attribute)

So i simply want to add a checkbox above "Collect IP Addresses" (or any other place) in the form settings. I think i need a plugin which extends the freeform-plugin. But i can not find a hook/example how to add fields/variables/attributes in the adminpanel, which can be checked by the admin/user and are available in the further process.

To explain it more in detail: I use a custom plugin to extend the behaviour after submit - so a custom action happens. If the checkbox is checked, a second action should be triggered. I do not want to define the handles of specific forms, because the adminuser should be able to create a new form and enable my switch.

I tried to create i lightswitch field on the same page, where i insert the form. But because of using "freeform.form(xxx).render" i am not able to transfer my variable into the "EVENT_AFTER_SUBMIT"

Hope you understand my thoughts and someone has a good idea on how to solve this. Maybe it is even impossible, even this would help me ;)


texts:
I've run into this error from time to time:

Failed to load resource: net::ERR_CACHE_MISS

I've seen it being thrown by several different files.  I don't know how to trigger it to better explain how to recreate the problem.

What does it mean?  What can I do to get it to disappear?


texts:
I am trying to use the new multisort filter to sort an array in reverse order using a date key, but can't seem to figure out the correct syntax. Here is what I have:

{% for rides in allRides|multisort(eventDate,SORT_DESC,SORT_REGULAR) %}

This throws an error saying "Variable eventDate does not exist". eventDate is definitely a key in the array 'allRides'

If I do this, it works fine, but gets sorted by eventDate ascending:

{% for rides in allRides|sort %}

Some guidance on using the multisort filter would be greatly appreciated!


texts: How can I get a list of unique products a Craft Commerce customer has purchased?

texts: I'm trying to figure out a way from Twig to get a distinct list of products purchased by a user. Help?


texts:
I'm trying to update some checkbox fields through the frontend with ajax.
After clicking / change of the checkbox the form needs to update the profile.

Template code:

<form class="form-horizontal form-ajax" method="POST" action="" accept-charset="UTF-8" id="notificaties">
{{ getCsrfInput() }}
<input type="hidden" name="action" value="/users/saveUser">
<input type="hidden" name="redirect_" value="account">
<input type="hidden" name="userId" value="{{ user.id }}">

            Ontvang updates over leuke nieuwe producten

                <input type="hidden" name="fields[emailUpdates]" value="0">
                <input class="ajaxcheck" type="checkbox" id="fields_emailUpdates" name="fields[emailUpdates]" value="1" {% if user is defined and user.emailUpdates %} checked="checked"{% endif %}>

            Ontvang email updates over geinteresseerde kopers

                <input type="hidden" name="fields[emailReactie]" value="0">
                <input class="ajaxcheck" type="checkbox" id="fields_emailReactie" name="fields[emailReactie]" value="1" {% if user is defined and user.emailReactie %} checked="checked"{% endif %}>

            Ontvang wekelijks een upate over de producten van jou favoriete verkopers

                <input type="hidden" name="fields[emailFavorieten]" value="0">
                <input class="ajaxcheck" type="checkbox" id="fields_emailFavorieten" name="fields[emailFavorieten]" value="1" {% if user is defined and user.emailFavorieten %} checked="checked"{% endif %}>

            Ontvang email updates van de reacties van jou producten

                <input type="hidden" name="fields[emailComments]" value="0">
                <input class="ajaxcheck" type="checkbox" id="fields_emailComments" name="fields[emailComments]" value="1" {% if user is defined and user.emailComments %} checked="checked"{% endif %}>

 </form>

JS code:

 $(".ajaxcheck").click(function(){
    var data = $(this).parents('form').serialize()

    $.ajax({
        context: this,
        method: "POST",
        dataType: "json",
        url: "/actions/users/saveUser",
        success: function(data, response){
            $(this).parents('.account-item').remove();
            console.log("success", response, data);
        }
    });
});

But it gives me an error: GET http://shop.craft.dev/actions/users/saveUser 400 (Bad Request)

The form gets updated. So it works. But it still gives me this error:

In my craft.log file:

exception.Craft\HttpException.400
Message exception 'Craft\HttpException' in /Volumes/HDD Drive/Sites/Shop/app/controllers/BaseController.php:191


texts: Problem with entry relations in using craft + postgres

texts:
I have a custom module saving entries into the system and those entries contains several category relationships. I have done the same previously with MySql and never had problems.
I am currently setting the fields in the entry to an array with the ID of the category it should relate to. The entry gets saved but when I go to the CP and check it none of the relations were saved. I have the flag to validate the entries upon saving set to true so it shouldn't save without the proper categories since they are mandatory fields.
System info:
PHP version 7.4.9
OS version  Linux 4.19.76-linuxkit
Database driver & version   PostgreSQL 12.4
Image driver & version  Imagick 3.4.4 (ImageMagick 6.9.10-23)
Craft edition & version Craft Pro 3.5.11.1
Yii version 2.0.38
Twig version    2.13.1
Guzzle version  6.5.5
Imagine version 1.2.3-dev
Sample code is:
$device->productCategories = [$productCategoryId];

I also tried
$device->productCategories = [Category::find()->id($productCategoryId)->one()->id];

The weirdest part is that my entry has a dynamic title that is build based on the categories titles.
For example category + brand + model capacity + color... The entry title is saved using the proper values with the full title based on the related and products.
I have spent a couple of hours debugging, made fields non mandatory, etc...
The plain text inputs get saved properly. The only issue is with relations.


texts: After switching from PHP 5 to 7 for a local 2.x install, I can't login

texts:
I have Craft running locally, the latest 2.x branch. When I change the server to run PHP 7 instead of 5.x, the local Craft frontend still works, but I can't login to the backend. It says "Invalid username or password", even after doing the reset password process.

Trying to prep a site for upgrading to Craft 3, but if I can't even get Craft 2.x running on PHP 7... :-/


texts: Comparing date field object with global variable "now" gives unexpected result

texts:
The goal is to show a word when date field qualifies for tomorrow or today instead of numeric date.

Setting and calling variables:

{% set deliveryDate = order.deliveryDate %}
{% set tomorrow = now|date_modify("+ 1 day") %}

{% if deliveryDate == tomorrow %}
  {% set deliveryDate = "tomorrow" %}
{% elseif deliveryDate == now %}
  {% set deliveryDate = "today" %}
{% else %}
  {% set deliveryDate = deliveryDate|date("d.m.Y") %}
{% endif %}

My date field has selected value of tomorrow whereas the first statement should be truthy.

So I think I'm comparing two objects with the same values but different classes?
I had figured it out by formatting the date objects to strings using day() filter.

But why is THAT happening on the first place?


texts: How to find and delete with Active Record

texts:
I'm trying to learn how to add and delete records using Active Record.

This works to add:

$instance = new Calendar37Record;
$instance->timestr = $timestr;
$success = $instance->save();

Given that I know the id of the record to delete, is the process to find the record and then delete it? Or can you just delete it?  I tried this, but it doesn't seem to find the record, and it complains 'The active record cannot be deleted because it is new.':

$instance = new Calendar37Record;
$instance->findByPk($id);
$success = $instance->delete();

Thank you for any help!


texts: Sprout Email Plugin and Multilanguage. How to translate SubjectLine?

texts:
I use Sprout Email on a website to send transactional email (about 15 different types).

The website gets now translated to 3 languages (DE/FR/EN). It is all fine, but of course, also the transactional emails need to be in three languages.

As Sprout Email does not really support localization, it is still somehow possible by adding 3 "Email Body" fields to the email field layout:

emailBodyDe
emailBodyFr
emailBodyEn

In the mail template, I can then chose which body to use. All good so far.

{% set locale = object.locale %}
{% set emailBody = email.htmlEmailBodyDe %}
{% set emailSubject = email.subjectLine %}
{% switch locale %}
    {% case "fr" %}
        {% set emailBody = email.htmlEmailBodyDe %}
        {# ... set subject!? ... #}
    {% case "en" %}
        {% set emailBody = email.htmlEmailBodyEn %}
        {# ... set subject!? ... #}
{% endswitch %}

But I can't translate the subject line. There is just one fixed field in Sprout Email for that.

Any suggestions how I can also make the subject field multi-language?


texts: Is there a very very basic example of simply outputting PHP with a plugin to Twig?

texts:
For arguments sake let's say I wanted a plugin that is a basic output:

<?php echo '
Hello World
'; ?>

So all I am wanting to output is that, and I want that output to be available via twig (ie: {{ helloworld }}

Not passing any information, not doing anything with the craft database, etc. Just very basic.


texts: Order related entries by number of categories they have in common with current entry

texts:
I'm creating a list of similar entries which displays entries that share the same categories as the current entry. My code looks like this:

{% set categories = craft.categories.relatedTo(entry) %}
{% set entries = craft.entries.section('projects').relatedTo( categories ).id('not ' ~ entry.id) %}
{% for project in entries %}
    {{ project.title }}

{% endfor %}

Many of my entries have multiple categories. Is it possible to order the list so that entries with the most categories in common with the current entry are at the top? And if not, is there another solution that would do this?


texts: How do I add the Categories and tags related to each entry?

texts:
This is my basic entry layout and I just want to display the linked category and tag names as indicated…

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

            {{ entry.postDate | date("d") }}
            {{ entry.postDate | date("M") }}

            {{ entry.title }}

Category: Category Name

Tags: Tag 1, Tag 2, Tag 3

Share

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

{% endfor %}


texts:
I recently renewed many licenses on a previously-neglected site and have been attempting to update both the CMS and the plugins. Despite having a Freeform Pro license, the plugin appears as Freeform Lite on the update list, and attempting to update it from 2.3.0 to 2.5.27 results in the error message:

Error: Client error: POST https://api.craftcms.com/v1/composer-whitelist resulted in a 400 Bad Request response: {"message":"Unknown package/constraint: solspace/craft3-freeform@2.5.27"}

The CMS is currently at 3.0.41.1, and attempting to update to 3.4.22.1 results in an error also referencing Freeform:

Composer output: Package "craftcms/vue-asset" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package solspace/craft3-freeform 2.5.27 exists as solspace/craft3-freeform[3.0.0-beta.1, 2.5.24, 2.5.23, 2.5.22, 2.5.21, 2.5.20, 2.5.19, 2.5.18, 2.5.17, 2.5.16, 2.5.15, 2.5.14, 2.5.13, 2.5.12, 2.5.11, 2.5.10, 2.5.9, 2.5.8, 2.5.7, 2.5.6, 2.5.5, 2.5.4, 2.5.3, 2.5.2, 2.5.1, 2.5.0, 2.4.3, 2.4.2, 2.4.1, 2.4.0, 2.3.4, 2.3.3, 2.3.2, 2.3.1, 2.3.0, 2.2.2, 2.2.1, 2.2.0, 2.1.1, 2.1.0, 2.0.4, 2.0.3, 2.0.2, 2.0.1, 2.0.0, 2.0.0-beta.20, 2.0.0-beta.19, 2.0.0-beta.18, 2.0.0-beta.17, 2.0.0-beta.1, 2.0.0-beta.2, 2.0.0-beta.3, 2.0.0-beta.4, 2.0.0-beta.5, 2.0.0-beta.6, 2.0.0-beta.7, 2.0.0-beta.8, 2.0.0-beta.9, 2.0.0-beta.10, 2.0.0-beta.11, 2.0.0-beta.12, 2.0.0-beta.13, 2.0.0-beta.14, 2.0.0-beta.15, 2.0.0-beta.16] but these are rejected by your constraint.
Problem 2
- The requested package solspace/craft3-freeform (locked at 2.3.0, required as 2.5.27) is satisfiable by solspace/craft3-freeform[2.3.0] but these conflict with your requirements or minimum-stability.

Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.

Based on other posts here, I've attempted to remove the "3" from "craft3-freeform" in the composer.json file (since reverted) and have attempted to run "composer update", though it appears I do not have shell access here. I know these are some outdated versions here, but any recommendations?

Thanks for your time and insight.


texts: Does anyone think there will be an automatic update from 2-3? Or as the file structure is different do you think it'll be unlikely?


texts: Loop through assets field on detail/product page

texts:
I am trying to loop through an assets field called gallery on entries in a commerce products channel.

This field can have multiple images in it. I can get this to work on a channel listing page domain.com/shop/ but can't get this to work on the entry detail page domain.com/shop/products/detail/.

Any help is appreciated.

{% for asset in product.gallery.first() %}
    <img src="{{ asset.url }}">
{% endfor %}


texts: How to list/filter by the entry type column in the entries listing

texts:
I've got a 'media' channel that has two entry types: Film and Report.

I have set the listing of entries to have the entry type column, but it doesn't seem to have any options for making it clickable to sort by entry type. Is this a current feature?

Thanks


texts: Where do you all host your CratCMS sites?

texts:
I'm very curious to know what are the most popular hosting services chosen by CratCMS developers. Perhaps I'm missing out in some gems!

Please let me know what you love about your favorite hosting service and at least one thing you dislike about it.


texts:
On my Products details page I have 2 selects.
The 1st select list out the Primary variants. Based on the selected Primary variant the 2nd select is auto-completed in with Secondary variants that have the same Primary variant.

I am doing setting this initially via an array:

{% set myVariants = [] %}

{% for variant in product.variants %}

{% set variantId = variant.id %}
{% set Primary = variant.primary %}
{% set Secondary = variant.secondary %}

{% if Primary not in myVariants | keys %}
    {% set myVariants = myVariants | merge({
        (Primary): [Secondary]
    }) %}
{% else %}
    {% set myVariants = myVariants | merge({
        (Primary): myVariants[Primary] | merge([Secondary])
    }) %}
{% endif %}

{% endfor %}

This outputs an array like so when dumped:

array(5) {
  ["0.375"]=> array(2) {
    [0]=> string(5) "0.125"
    [1]=> string(5) "0.415"
  }
  ["0.500"]=> array(1) {
    [0]=> string(5) "0.768"
  }
  ["0.625"]=> array(1) {
    [0]=> string(5) "1.151"
  }
}

So based on the selected Primary and Secondary variants a specific variant ID should be pulled.

I've tried starting with the variant IDs, then passing the Primary variant to reproduce a similar array like above but it doesn't put them in a 2nd array.

What am I missing?

Also, based on the selection of Primary and Secondary, not only will the ID need to be pulled but also 2 additional variants and the sku; each of which are specific to that variant.


texts:
I created html template using radio buttons as tabs as you can see in the picture. When user click on any of the tabs the relevant entries for that month display and the rest hidden.

I created matrix field to group the calendar field and other text fields but my question is how to dynamic display all entries for each month? So that I can use CSS to hide other entries and show entries when tab are selected.


texts:
If I am confident in the users of our webpage that they will never be messing with the Twig templates, then what risk is there to creating a |php filter for Twig that just does this?

{% set text = "echo 'Hello World';" %)
{{ text | php }}

Filter function:

function myPhpEvalFunction ($text = null) {
   return eval($text);
}


texts:
I am working on a project and the plug in I installed won't work because I don't know how to add the jquery.css file needed.

What I did is to add the file with a <link> command but it's still not working.

Any help would be great.

    {% block body %}
<link type="text/css"  href="{{ asset('home/workspace/fermate/src/CtrlBln/HomepageBundle/Resources/public/js/Minimal-jQuery-Image-Viewer-with-Image-Preloading-ABigImage/bigimage.jquery.css')}}" >

    {% for link in entity.getSidebarImages() %}
        {% if link.image.isFoto() %}

                    {{ link.image.description|raw }}

        {% else %}

                      {{ link.image.title|raw }}

        {% endif %}
    {% endfor %}

{% endblock %}

    {% block body_javascripts %}
        {% javascripts output='aBigImage.js'
        '@CtrlBlnHomepageBundle/Resources/public/js/Minimal-jQuery-Image-Viewer-with-Image-Preloading-ABigImage/abigimage.jquery.min.js'
        %}

        {% endjavascripts %}
    {% endblock %}


texts: Twig's 'start with' conditional returns 500 error

texts:
The following is within the index template on a site in production:

{% set domain = craft.request.getServerName() %}
{% if domain starts with 'subdomain' %}
    {% include 'subdomain/index' %}
{% else %}
    {% include 'homepage' %}
{% endif %}

It works without any problem on that server. I've just copied the site over to a another server for development, but that same code seems to be responsible for a 500 error. The following works, so I think it's to do with Twig's start with conditional:

{% set domain = craft.request.getServerName() %}
{% if domain == 'subdomain.domain.com' %}
    {% include 'subdomain/index' %}
{% else %}
    {% include 'homepage' %}
{% endif %}

I'm assuming it's a PHP setting - does anyone know which?


texts:
Would I be right in assuming to allow clients to safely paste text from MS word into a WYSIWYG all I need to do is add:

pastePlainText: true

to my Redactor json config file? I have done this and it seems to be working but I am aware of the problems concerning MS Word and pasting to wysiwyg's and don't want to encounter them further down the track.


texts: Can I move existing tags, which are currently in a global tag group, to new the new tag groups I've set up?

texts: I've set up new tag groups to help organise the c300b tags we have set up. How do I move the existing tags, which are already in use, to the new tag groups?


texts: Adding markers to map from field in entries within section

texts:
I feel like I'm overlooking something simple here, but I can't for the life of me figure out how to add markers to a map. I had this working with the Google Maps for Craft plugin but since switching to Smart Map I get as far as rendering a map and that's it.
My set up is such: I have a structure with multiple same-level entries, each of which has an address. I have an index page that's rendering a map which should be populated with markers based on the the addresses from each entry's address field.
Historically, I looped through the entries, defined each marker's address and then added that to the map variable like so:
{# Look for each location listed #}
{% for entry in craft.entries.section('locations').limit(null) %}
    {# For each location found, set the map marker properties to have an
       address and a link to the location page within the pop-out menu that
       shows on-click #}
    {% set marker = {
        address: entry.locationAddress,
        content: '...'
    } %}
    {# Then we add the marker to our map variable #}
    {{ craft.googleMaps.marker('map', marker) }}
{% endfor %}

However, now with Smart Map, I can't figure out how to recreate this. I don't quite understand how to set the locations for the {{ craft.smartMap.map(locations, options) }} call. The docs show that one can pass an array into it via craft.entries.section('myLocations') but since my address fields are not entries in a section I'm not sure how to parse that out.
Any help or insight would be greatly appreciated, thanks!


texts: Trouble with twig syntax for discount conditions

texts:
I'm trying to add a condition for a discount. It involves a custom date field. I want to discount anything that falls on Tuesday. I can't seem to get the twig syntax right. I've tried these two:
((cart.eDate|date('D')) == 'Tue')
((cart.eDate|date('D')) in ['Tue'])

I prefer the latter so I could add additional days if needed. Either of these work in templates. Is it because it is a custom field and the CP doesn't recognize it? Is there another approach?


texts: 'onDeleteEntry' Event is not triggered when an Entry is deleted?

texts:
I have the following code:

namespace Craft;

class AffiliatesExportPlugin extends BasePlugin
{
  //All other functions

  public function init() {
    craft()->on('entries.onDeleteEntry', function(Event $event) {
      Craft::log(" on delete ######\n\n", LogLevel::Info, true);
    });
  }
}

I added this as a plugin activated the plugin, but when I delete an entry, it doesn't seem to get triggered. What am I doing wrong?


texts: Database Exception: Column not found: 1054 Unknown column 'position' in 'order clause'

texts:
I deployed the project from the git repository on hosting. When trying to open the homepage I get the following error:

Database Exception
    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'position' in 'order clause'
The SQL being executed was: SELECT `elements`.`id`, `elements`.`fieldLayoutId`, `elements`.`uid`, `elements`.`enabled`, `elements`.`archived`, `elements`.`dateCreated`, `elements`.`dateUpdated`, `elements_sites`.`slug`, `elements_sites`.`siteId`, `elements_sites`.`enabled` AS `enabledForSite`, `elements_sites`.`uri`, `categories`.`groupId`, `content`.`id` AS `contentId`, `content`.`title`, `structureelements`.`root`, `structureelements`.`lft`, `structureelements`.`rgt`, `structureelements`.`level`, `structureelements`.`structureId`
FROM (SELECT `elements`.`id` AS `elementsId`, `elements_sites`.`id` AS `elementsSitesId`, `content`.`id` AS `contentId`, `structureelements`.`structureId`
FROM `elements` `elements`
INNER JOIN `categories` `categories` ON `categories`.`id` = `elements`.`id`
INNER JOIN `elements_sites` `elements_sites` ON `elements_sites`.`elementId` = `elements`.`id`
INNER JOIN `content` `content` ON (`content`.`elementId` = `elements`.`id`) AND (`content`.`siteId` = `elements_sites`.`siteId`)
LEFT JOIN `structureelements` `structureelements` ON (`structureelements`.`elementId` = `elements`.`id`) AND (EXISTS (SELECT *
FROM `structures`
WHERE (`id` = `structureelements`.`structureId`) AND (`dateDeleted` IS NULL)))
WHERE (`elements_sites`.`siteId`='1') AND (`elements`.`archived`=FALSE) AND (`elements`.`enabled`=TRUE) AND (`elements`.`dateDeleted` IS NULL) AND (`elements_sites`.`enabled`=TRUE) AND (`structureelements`.`level`='2') AND (`elements`.`draftId` IS NULL) AND (`elements`.`revisionId` IS NULL)
ORDER BY `position`) `subquery`
INNER JOIN `categories` `categories` ON `categories`.`id` = `subquery`.`elementsId`
INNER JOIN `elements` `elements` ON `elements`.`id` = `subquery`.`elementsId`
INNER JOIN `elements_sites` `elements_sites` ON `elements_sites`.`id` = `subquery`.`elementsSitesId`
INNER JOIN `content` `content` ON `content`.`id` = `subquery`.`contentId`
LEFT JOIN `structureelements` `structureelements` ON (`structureelements`.`elementId` = `subquery`.`elementsId`) AND (`structureelements`.`structureId` = `subquery`.`structureId`)
ORDER BY `position`

But the admin page opens without errors.
And when I run a project on a local machine, there is no such error.
What can i do to fix this problem?


texts: Using field types to override meta defaults

texts:
I was wondering if someone could help me find a solution to this. I didn't see it in the docs. Perhaps I missed it...

I created an entry type with the field type Meta: Basic. I would like to use this to override the meta defaults at the entry level. It doesn't appear to do it on it's own and accessing the content via entry.metaBasic.description doesn't work either. What am I doing wrong? Thanks in advance.


texts: All fields disappearing except 'Title' after saving

texts:
All other fields disappear except the 'Title' field after I save a large block of text with a lot of links in the body (richtext) field.

I can't seem to pinpoint it on to anything specific, this is what I'm putting inside the 'Source' of the richtext http://pastebin.com/jiyA6xii

Any help would be greatly appreciated.


texts: Counter for entries to show most read Articles

texts: How can I add a counter or something similar to my entries, so that I could loop through the most read articles?


texts: I'm a newbie to Craft so apologies if this has been answered or is too simplistic for the forum but how do I change my site's favicon? Thank you.


texts: How do I force Craft to regenerate assets transform?

texts:
I had to add an image size in the assets transforms; all my pics were previously uploaded, but when I use getUrl('headIpad'), it makes urls like this:

http://host.com/cpresources/transforms/4/

Instead of this:

http://host.com/uploads/team-photo/_headIpad/fall-back.jpg

I tried to use generateTransformsBeforePageLoad in my config but Craft generates an error:

  Internal Server Error
  Image “fall-back.jpg” cannot be found.

Any ideas?


texts: Is there a way to output certain rows (or filter) from a table?

texts:
Here's an example, I have three columns in a table: ClassQuarter, Course No, Description.

I would like to output rows only with ClassQuarter == '1' in a HTML table, then output rows where ClassQuarter == '2' in another table, then output rows where ClassQuarter == '3' in another table.

Am I able to output rows with a condition for the first column?


texts:
When i use lastUsedShippingAddress it populates the last customer order address. However when the order is complete, database create new customer address (same info but with different ids).

Is this how it suppose to work?


texts: How to store S3 credentials in environment variables?

texts: For a Craft 2 S3 asset source, access keys are expected to be entered in from the Control Panel. Is there a way to supply the access key and secret through environment variables instead?


texts: Setting selected elements in a BaseElementSelectorModal (or BaseElementIndex)

texts:
I'm writing a Javascript based plugin which creates an instance of Craft.BaseElementSelectorModal.

When the modal is created, I'd like to have some of the entries in the modal's element index auto-selected (i.e. their containers should have the sel class added, just like when the user actually selects an entry). I have an array of entry IDs to work with, but I'm struggling to find a way to actually set the element index' selected entries.

As far as I can tell, there aren't any parameters I can set to the BaseElementSelectorModal (aside from disabledElementIds, which I can't use as I don't actually want the entries to be disabled, only selected).

I can get to the modal's BaseElementIndex instance – is there a way to programmatically select an array of entries?


texts: Combine two almost identical sidebar templates, used for blog index and category index pages

texts:
I'm struggling to combine two almost identical sidebar templates.

I’m working on a site that has:

a blog channel section with an index template that ‘includes’ a ‘sidebar-main.html’ template
a structure section with a page template that ‘includes’ the same ‘sidebar-main.html’ template
a category template that lists blog posts for a single category, but which ‘includes’ a different ‘sidebar-category.html’ template

The ‘sidebar-main.html’ and ‘sidebar-category.html’ templates are almost identical. Their main function is to offer the user a choice of an 'All categories' menu sorted by category, or a 'Top categories' menu sorted by number of posts, selectable in the entry control panel.

The 'sidebar-main.html template starts:

    {% if entry.sidebarContent is defined %}

        {% for block in entry.sidebarContent %}

            {% if block.type == "sidebarWidget" %}
                {% if block.widget.contains('topCategories') %}

Top categories

                    {% set entryIds = craft.entries.section('blog').ids() %}
                    {% set allCats = craft.categories.relatedTo(entryIds).level(1).find() %}
                    {% set catArray = {} %}

                    {% for category in allCats %}
                      {% set catArray = catArray | merge({(category.slug):craft.entries.relatedTo(category).total() }) %}
                    {% endfor %}

                    {% set catArray = catArray|sort|reverse %}

                    {% for catSlug, entryCount in catArray | slice(0,3) %}
                    {% set category = craft.categories.slug(catSlug).first() %}

                    {% if loop.first %}

                    {% endif %}

                                        {{ category.title }}&nbsp;

{{ entryCount }}{% if entryCount == 1 %}&nbsp;post{% else %}&nbsp;posts{% endif %}

And the 'sidebar-category.html' template is identical to this, except that entry.sidebarContent is replaced by category.sidebarContent. This works fine, with no errors or problems (except it's not DRY). However, if I can eliminate the use of 'category.sidebarContent', then I can split up the combined template to enable its use in 404 and search etc pages.

I hope all that makes some sort of sense, and thanks for any suggestions!


texts:
First time using Commerce and made pretty good progress, but... I need to collect a few bits of information at the cart stage. The site is selling conference tickets, and I need to know:

if the delegate has any dietary requirements
whether or not they have been asked to speak
and if they have, to provide a short bio

I'm aware of the {{ item.note }} tag, which I'm using for the dietary requirements. But how can I capture the other two fields?

Any help much appreciated!


texts: How to get entries that have a category selected from a category field within a matrix block?

texts:
I've got a Section that uses a Matrix field, that has a block, that has a categories field in it.

I want to find all entries using this Matrix field, who has a categories field and has a certain category selected.

Tried the sloution given in the following URL, but no luck:
[Find entries that have a category selected from a category field within a matrix block

I have a category group faqCategory. Inside that 3 categories Transport Category (transport-category), Room Category (room-category) and Services Category (services-category).

I have Matrix custom field defined called faqList, which has Block Type FAQ, inside FAQ block 3 fields faqCat(Type of above faqCategory), Question(Type of Text) and Answer(Type of Text).

Another text field called pageTitle.

There is a Single Type section called faqsPage, which has entry Types pageTitle and faqList.

Based on the above provided solution for the original question I have programmed it as follows:

{% nav category in craft.categories.group('faqCategory') %}

    {{ category.title }}

    {% set entries = craft.entries.section('faqsPage').relatedTo({
        targetElement: category,
        field: 'faqList.faqCat'
    }) %}

    {% for entry in entries %}

        {{ entry.title }}

    {% endfor %}

{% endnav %}

Following is the output:

Transport Category

FAQs Page

Room Category

FAQs Page

Services Category

FAQs Page

  Instead of proper entries it returns page itself. Please help.


texts:
I have a set of events I want to query based on user-input date times.
How do I achieve something like this?

{% set entries = craft.entries.section('events').minScheduleDate('>=', 'now').maxScheduleDate('<=', 'now') %}

Where maxScheduleDate is a field for user to input date?


texts: This is a newbie question regarding running Craft updates. In the past I've been caught out by stupidly running updates on the live server. I'm now trying to get into the habit of running the updates on a local version, then pushing that to the live version - the proper way of course. Am I right to assume that the only files that have been changed after an update are composer.json and composer.lock (along with the db)?


texts:
I've set up four custom image transforms on the page and would like the content editor to be able to select which size they want the image to be from a drodown field preconfigured with the transformation names. This is all within a Matrix field, btw. This answer was close, and helped me put .value on the end of my dropdown field variable, but it must only work with pre configured image transforms in Craft's settings.

Here is the code (simplified):

{# medium 16:9 #}
{% set landscapeMd = {
  width: 439,
  height: 247,
  quality: 80,
} %}

{# medium 9:16 #}
{% set portraitMd = {
  width: 278,
  height: 494,
  quality: 80,
} %}

{% for block in entry.productCollage %}
  {% switch block.type %}
    {% case "digitalProduct" %}
      // selected via dropdown field
      {% set transformType = block.imageAspectRatio.value %}

        {% for image in block.image %}

        {% endfor %}

  {% endswitch %}
{% endfor %}

What I get with this code is an error that says the selected image transform is not available. However, if I type in that image transform verbatim, it works fine.


texts: How to remove entries with craft migration safeDown elegantly

texts:
I am migrating some entries into Craft for the first time and my saveUp is quite simple where I use the saveElement function. The problem is after doing a few safeUp's and safeDown's I'm getting some appended numbers on my slugs e.g. 'title-07' when ideally it would just stay as 'title'. The slug is based on the title and it appears my safeDown method doesn't hunt down the old slugs wherever they are.
My safeUp() looks something like this:
/*
 * Set the entry and save it
 */

$entry = new Entry();

// Set the entry data
$entry->sectionId   = '4';
$entry->typeId      = '4';
$entry->authorId    = '1';

// Title etc..
$entry->title = $title;

// Run saveElement with data
$success = Craft::$app->elements->saveElement($entry);

My safeDown is a bit less elegant:
/*
 * Find the matching entries to delete
 */

$entry = (new \craft\db\Query())
->select("id")
->from("content")
->where( "title = " . $title )
->all();

/*
 * Loop through matches and delete
 */

foreach( $entry as $key => $value ) {

    $rowsAffected = (new \craft\helpers\Db())
    ->delete('content', 'id=' . $value['id'] );

}

My question is a couple things.
Is there something as nice as saveElement where I can just pass a typeId and id for the content and everything related gets removed?
My current method where I use craft\helpers\Db->delete leaves behind the original slug. If there's not a cleaner method like saveElement, where can I find the slugs to get rid of them as well?
Any pointers greatly appreciated.


texts: Sorting across blocks (to get prev/next links)

texts:
issue is an entry that has a matrix field named contents, whose blocks have an entries field named works, and the related works channel has an entries field named authorPeople.

Issue 1's contents consists of 2 blocks: A 'regular' section and an 'alumni' section. On the cover page, I loop through the blocks. For each block, I get the entries related to their authors, so that I'm outputting entries sorted by author last name, where some authors have more than one entry associated:

{% set contributors = craft.entries({
    section: 'contributors',
    relatedTo: { sourceElement: block.works, field: "authorPeople" }
}) %}

{% set articles = craft.entries({
    section: 'works',
    relatedTo: contributors
    order: 'lastName'
}) %}

That works fine, because I've got access to block.works. Any optimization tips are welcome :)

On the individual entry page, I want to getPrev and getNext entries spanning both blocks. So if you're at the last entry in the 'regular' section, your next link is the first entry in the 'alumni' section. And if you're on the first entry in the 'alumni' section, your prev link is the last entry in the 'regular' section. The last entry in the last section won't return a next link, so I can code in a link to another page, and the first entry in the first section won't return a previous link, so I can code in a link to the cover page.

Without having to loop through the blocks, how can I get that? Trying to order by issue.contents doesn't seem to work.


texts: Invalidating the cache tag from a plugin?

texts:
I have a plugin that renders HTML via a hook.  If someone wraps that hook with {% cache %} in their templates, how can my plugin tell Craft to invalidate the cache when something within it changes?

EDIT: Let's say, for example, that I'm getting JSON data from an external source via my plugin.  I could be rendering this via a hook, or using a Variable, it doesn't matter that much.

There's no Element that the content that changes can be linked to, in order to invalidate the cache.


texts:
I made my own, fairly simple field inside a Module for Craft 3.x.

What settings do i need to define to make it usable inside a table?


texts: Restricting file size for an Assets Volume

texts:
I have a use case where I want to limit the allowed file size for a certain Assets Volume to 20kb. All other volumes should be allowed files no matter the size.

I have looked at some other threads already that suggest developing a plugin to do this, or use the Yii event system for file uploads.

I have made other simple plugins before that interacted with entries, but I cannot understand how to make a plugin that latches onto the file uploading event.

Does anyone have any good documentation for where to begin with this? It is version 3.0


texts: Deployment of Craft 3 site to the production server

texts:
I am quite new in Craft CMS 3. I have developed a new site and now I want to move it to the production server. I have just moved all the files by FTP, moved the database, changed .env variables.

But when I go to the URL I get a message: "Forbidden You don't have permission to access / on this server."

If I go to URL/web then I get the first page but without images.

URL/admin shows "Not Found The requested URL /admin was not found on this server."

How do I deploy the site? I cannot find a good article/help about deployment for Craft 3.


texts: Why do Image transformations rename the image?

texts:
I noticed that when performing an image transition on an image, the resulting image name is computer gibberish. How can I maintain the original name of the image? Keeping the original name is important for SEO value.

EDIT
When viewing a transformed image for first time, the url shows as  http://aed.dev/cpresources/transforms/3?x=pEYIdgIMS ... but! I have discovered that this url only appears the first time I view the page. every other page view will display the image with original file name


texts: How can I change the Date Created for Assets?

texts:
I'm using graphql to pull in some assets/pdfs and ordering them by dateCreated, however the files go back a few years (i.e. files from 2019, files from 2018 etc.) but they weren't uploaded in the correct chronological order. Is there a way I can change the 'dateCreated' or 'Created at' date?  I changed the dateCreated column within the assets table of the database, but that didn't change anything within Craft or the graphql query.
Any help is appreciated.


texts: How can I set the isCompleted status of an order from within a custom module?

texts:
The default behaviour for commerce is to mark the isCompleted flag on an order to true once the order has been paid for.

I have need to alter this behaviour and only want to mark an order as Complete via manual intervention of a site admin - or after a predefined date has passed.

Is it possible to set the isCompleted flag from within a custom module?
Right now, I'm listening to the EVENT_AFTER_ORDER_PAID then attempting to set the isCompleted flag and save the order.

What I can't figure out is how to save the order!

Code so far, for what it's worth:

Event::on(
            Order::class,
            Order::EVENT_AFTER_ORDER_PAID,
            function(Event $e) {
                $order = $e->sender;

                $order->isCompleted = false; // no idea if this is correct

                $order->saveOrder(); // this doesn't work
            }
        );


texts:
I have a simple entry form on the frontend that will not save form data. After submit it returns to the form page with no errors, rather than going to the url I set in the redirect variable.

I have done this dozens of times on other sites - the section ID is correct, the user has permission to create an entry (even tried as SuperAdmin, same failure). I then tried using the sample form from the Craft docs page, still no luck. I even recreated everything verbatim on another Craft site and it works fine.

Server configuration seems fine and there are no other issues with the website.

I am pulling out what is left of my hair trying to figure out what is going on - any suggestions would be greatly appreciated!


texts: How to create ordered list of categories from multiple category groups

texts:
I have got multiple category groups and I need to concatenate them into one list for a filter UI element.

At the moment I have the following:

{% set categories = craft.categories.group('colour').all() %}
{% set categories = categories|merge(craft.categories.group('suitability').all()) %}
{% set categories = categories|merge(craft.categories.group('finish').all()) %}
{% set categories = categories|merge(craft.categories.group('shape').all()) %}
{% set categories = categories|merge(craft.categories.group('material').all()) %}
{% set categories = categories|merge(craft.categories.group('edge').all()) %}
{% set categories = categories|merge(craft.categories.group('surface').all()) %}

So now I have a list of all the categories within these groups, I can loop over them as follows:

    {% for cat in categories %}

            <button class="button categories__btn">{{ cat.title }}</button>

    {% endfor %}

But the issue I'm having is that the array of categories is outputting them in the order they're being added. I tried this:

{% set categories = categories.orderBy('title asc').all() %}

But it returns "Impossible to invoke a method ("orderBy") on an array."


texts: Similar entries with the greatest coincidence tags

texts:
I have code

    {% set tags = entry.q_tags %}
    {% set entries = craft.entries.relatedTo(tags).order('score').find() %}
    {% for item in entries %}
      {% if item.id != entry.id %}
         .......
      {% endif %}
    {% endfor %}

But how to do that similar entries displayed order with the greatest coincidence tags?
Thank you. Sorry for my english


texts: Using Image Transform as another custom field

texts:
I've created a section with a thumbnail image and also a dropdown to allow the user to select the transformation to apply to that image.

I've pre-created all the asset transformations ready and this is the code I have :

{% set imageTransform = storyEntry.storyThumbnailTransform %}
{% set thumbnailImage = storyEntry.storyThumbnail.first() %}
<img src="{{thumbnailImage.url(imageTransform) }}" alt="" class="post__preview-img post__preview-img--grid">

However, it doesn't appear to be rendering the image. If I output storyEntry.storyThumbnailTransform to the page, it displays the value of the image transform as expected.

What am I doing wrong? Or is there another way to accomplish this?


texts: Update existing entry from plugin not saving and producing no error

texts:
So, i'm trying to set a fields content via a plugin on an entry which already exists.

My code is like this:

$entry = craft()->entries->getEntryById($entryId);

$entry->setContentFromPost(array(
    'subTitle' => 'woot'
));

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

I get no error and the value of $success is false but it tells me nothing else.
If I var_dump($entry) after the first line, the output shows it has pulled the correct entry.


texts: HTTPs Site - Redirects Go to HTTP First & Then HTTPs

texts:
So I've updated the site URL in my general.php as follows:

    'siteUrl' => "https://" . $_SERVER['HTTP_HOST'],

I also have our web server making sure everything goes to https://www.example.com. Our IT person set this up but as I understand it it's done through vhosts in Apache.

Here is our .htaccess file:

<IfModule mod_expires.c>
 ExpiresActive on
 # Perhaps better to whitelist expires rules? Perhaps.
 ExpiresDefault "access plus 1 month"
 # cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5)
 ExpiresByType text/cache-manifest "access plus 0 seconds"
 # Your document html
 ExpiresByType text/html "access plus 0 seconds"
 # Data
 ExpiresByType text/xml "access plus 0 seconds"
 ExpiresByType application/xml "access plus 0 seconds"
 ExpiresByType application/json "access plus 0 seconds"
 # Feed
 ExpiresByType application/rss+xml "access plus 1 hour"
 ExpiresByType application/atom+xml "access plus 1 hour"
 # Favicon (cannot be renamed)
 ExpiresByType image/x-icon "access plus 1 week"
 # Media: images, video, audio
 ExpiresByType image/gif "access plus 1 month"
 ExpiresByType image/png "access plus 1 month"
 ExpiresByType image/jpeg "access plus 1 month"
 ExpiresByType video/ogg "access plus 1 month"
 ExpiresByType audio/ogg "access plus 1 month"
 ExpiresByType video/mp4 "access plus 1 month"
 ExpiresByType video/webm "access plus 1 month"
 # Webfonts
 ExpiresByType application/x-font-ttf "access plus 1 month"
 ExpiresByType font/opentype "access plus 1 month"
 ExpiresByType application/x-font-woff "access plus 1 month"
 ExpiresByType image/svg+xml "access plus 1 month"
 ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
 ExpiresByType text/css "access plus 1 year"
 ExpiresByType application/javascript "access plus 1 year"
</IfModule>

<IfModule mod_deflate.c>
 AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
 AddOutputFilterByType DEFLATE application/javascript
 AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
 AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
 Addtype font/opentype .otf
 Addtype font/truetype .ttf
 AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.msfontobject application/x-font-ttf font/opentype font/truetype
</IfModule>

<IfModule mod_rewrite.c>
     RewriteEngine On

    #301 redirect with trailing slash
        RewriteCond %{REQUEST_URI} /+[^\.]+$
        RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

    #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]
  AddType text/x-component .htc

</IfModule>

However, in tracking how redirects are working, it looks like most redirects, including adding an extra / to the end of a URL via the .htaccess, those done in Craft templates themselves and those done through the redirect manager plugin 301 to http://www.example.com and then 301 again to https://www.example.com. Visits to http://www.example.com redirect straight to https://www.example.com and visits to https pages directly return a 200.

How can I configure Craft to out the first redirect to http and just go straight to https? Thanks!


texts:
How do I check if a field is blank? I thought it was something like

{% if article.articleImage is defined %}

Which in this case is testing an Assets field (and seems to work). Tried the same for a text field (in a Matrix row), and that doesn't work, as far as I can tell:

{{ if block.heading is defined }}


texts: Create different types of Donation purchasable? (for Gift Aid etc)

texts:
The new donations purchasable looks super handy for charity websites, thank you for this :)

In the UK we have a thing called Gift Aid that allows charities to claim an extra 25% on donations/purchases if the customer opts into the scheme.

Is there any way you could modify the new Donation purchasable so that two (or more) kinds of donation can be logged in Craft?

Eg something like craft.commerce.donation.type(normal) and craft.commerce.donation.type(giftaid) - and then ideally a way to export a CSV of each donation type via the control panel?


texts:
A project I've been working on has just 'turned bad' - due to a number of reasons I've removed myself from involvement in the project. Earlier in the year I purchased an upgrade to the Craft license to that site for the Pro version, which I now don't want the client to have access to. I've removed the license.key file from their staging server, but they still have a backup of that file on their local machine.

According to the documentation, if I use that license.key file on another website, the old client will just get a notification asking them if they want to transfer the license to their website (the one I've stopped working on), which gives me no control over it. Am I stuck with the client just being able to say "I want this license" and there being nothing I can do about it?

Shouldn't ownership & domain control of the license sit with the owner of that license rather than the person trying to take it?


texts: ImageOptimize not using image url specified in my multi-environment setup and my volume config

texts:
When I output my ImageOptimize field in the template, my images are not showing up. If you inspect the image url, it's missing a folder name I'm specifying as part of the url in my multi-environment setup and volume config.

If I manually change the image url in the browser tools to include the missing folder, the image shows up. Other images are rendered fine when using the standard asset field code so I'm not sure what could be wrong.

Things to note:

I am using Andrew's multi-environment setup.
I have two separate folders in my web root folder:

In the folder assets/, I'm serving my template assets like css, images, and fonts.
In the folder content/, I'm serving the files uploaded to the volumes I have setup in Craft - images, logos, documents etc.

My environment variables:

'BASE_URL' => $protocol . $httpHost . '/',

'BASE_PATH' => realpath(dirname(__FILE__)) . '/web/content/',

My aliases (set for all environments):

'aliases' => [
    '@basePath' => getenv('CRAFTENV_BASE_PATH'),
    '@baseUrl' => getenv('CRAFTENV_BASE_URL'),
],

My volume config:

'*' => [
    'images' => [
        'path' => '@basePath/images',
        'url' => '@baseUrl/content/images',
    ],
],

My ImageOptimize snippet:

The image path being used on the frontend (note the absence of the content/ folder):


texts: Build array from nodes from RSS where keys contain colons

texts:
Probably pure twig:

I am building an array from nodes taken from a RSS-feed where one of the keys contains a colon which of course breaks everything. Like so:

Node in feed:

<media:thumbnail url="stuff I like to get." />

My twig:

{% for node in feed %}
        {% set latestArticles = latestArticles|merge([{
                'timestamp': node.pubDate|atom,
                'title': node.title,
                'uri': node.link,
                'description': node.description,
                'thumbnail' : node.media:thumbnail,
            }]) %}
        {% endif %}
    {% endfor %}

So how do I get media:thumbnail?

I have tried different things but without luck.


texts:
The RelatedTo function keeps puzzeling me. I got it working with categories, but now I want to do something in reverse with users. But I don't fully understand the RelatedTo function.

I have a channel called "downloads". I also have some users in the back-end. I have added a custom field to the user section called "selectDownloads". This field is a relatedEntry field where the admin can select entries from the downloads channel.
Now I want to list all downloads in my template that the current logged in user may see (so the entries that were selected when creating the user).

I read the docs multiple times allready and with some luck and trial and error I got it working on categories. But there I loop through all my products and relate them to a targetSource which is my category by a field that is part of my products channel.
In this case however, I want to loop through all my downloads, related to a field that is part of my users section (instead of my downloads channel). So the relation is different.

A more dummy proof explanation with some examples of the RelatedTo function would be welcome. I never know which elements I should address:

 {% set ingredients = craft.entries.section('ingredients').relatedTo({
     sourceElement: cocktail,
     field: 'ingredients' }) %}

sourceElement or targetElement:

Is this a section or field you have to give in?

field:

Is that a field from the ingredients section or the cocktail section?


texts: Error when trying to generate a PDF in Craft Commerce

texts:
I am getting an error when trying to generate a PDF in Craft Commerce.

The error is:

  Undefined index: (/srv/data/web/vhosts/www.nihonshu-sake.lu/craft/plugins/commerce/vendor/dompdf/dompdf/lib/Cpdf.php:3855)
  $font = $this->fonts[$this->currentFont];


texts: Create assets subfolder on upload based on entry field value?

texts:
I have a projects section on my website, there can be multiple projects from one client. Each project has at least one image.

I wanted to know if it is possible when uploading assets to a new project entry to be able to create a new subfolder within my specified assets folder for that particular client?

So can I either:

a) Create a subfolder when uploading assets.
b) Use the value of the "client" field to dynamically create a subfolder when uploading images to the entry.

Any help/direction this would be appreciated.

Jay


texts:
How do you add extra parameters or update a parameter to an exiting POST URL?

ADD EXTRA PARAMETER

For example, I have a page at this address:

http://localhost/shop/?color=red&order=title

And in my twig I want to add a parameter like this:

http://localhost/shop/?color=red&order=title&sort=asc
http://localhost/shop/?color=red&order=title&sort=asc&limit=10

UPDATE PARAMETER

For example, I have a page at this address:

http://localhost/shop/?color=red&order=title

And in my twig I want to update a parameter like this:

http://localhost/shop/?color=blue&order=title
http://localhost/shop/?color=red&order=price


texts: Join Matrix Fields To Query Using andWhere

texts:
My question is this, I want to join a matrix table to a query and look for certain values in it.  I am using this example below.  I have 2 matrix fields partsModels.model and partsModels.parts. I need to make sure that all the criteria is met before looping through any of the data.

{% set entries = craft.entries.andWhere(['like', 'content.fields_myFieldHandle', 'foo']).all() %}

that Robin supplied here.


texts: How do you output the Image Caption on an asset?

texts:
When you double-click an asset you can set the Image Caption:

How do you structure the query to output this Image Caption "field?"


texts: Solspace Freeform - Change "submit" button to "next"

texts:
I'm building out multi-page forms using composer. And having a submit button at the bottom of page 1 (of 5) is weird.

Can I change the text for the next/previous buttons on pages using the freeform render tag?

I'd prefer that only the last page of the form have the submit button, and all the other pages have buttons that say "Previous" and/or "Next."


texts:
There are a few tickets touching on this, but the solutions proposed aren't working and I'd like to share the use case:

I have a Table of Contents page that is outputting a set of entries based on an Entries field, in the order they appear in that field. When you click on an entry on that page, it loads on its own page.

At the bottom of the individual entry page, I have Prev/Next URLs, using:

{% set data = craft.entries.section('works').relatedTo(issue.contents).limit(null) %}
{% set prevEntry = entry.getPrev(data) %}
{% set nextEntry = entry.getNext(data) %}

The prev & next entries there, though, are based on a sort in the 'works' section, not the entries field.

I've tried this, per the documentation:

{% set entries = craft.entries(
    {
        relatedTo: { sourceElement: issue, field: "contents" },
        order:     "sortOrder",
        limit:     null
    }
) %}

That gives me the following error. How can I sort .relatedTo entries based on the source field's order?

Integrity constraint violation: 1052 Column 'sortOrder' in order clause is ambiguous. The SQL statement executed was: SELECT `elements`.`id`, `entries`.`sectionId`, `entries`.`typeId`, `entries`.`authorId`, `entries`.`postDate`, `entries`.`expiryDate`
FROM `craft_elements` `elements`
JOIN `craft_elements_i18n` `elements_i18n` ON elements_i18n.elementId = elements.id
JOIN `craft_content` `content` ON content.elementId = elements.id
LEFT JOIN `craft_relations` `sources1` ON (sources1.targetId = elements.id)
LEFT JOIN `craft_matrixblocks` `target_matrixblocks1` ON target_matrixblocks1.id = sources1.sourceId
JOIN `craft_entries` `entries` ON entries.id = elements.id
JOIN `craft_sections` `sections` ON sections.id = entries.sectionId
LEFT JOIN `craft_structures` `structures` ON structures.id = sections.structureId
LEFT JOIN `craft_structureelements` `structureelements` ON (structureelements.structureId = structures.id) AND (structureelements.elementId = entries.id)
WHERE (((((elements_i18n.locale = :locale) AND (content.locale = :locale)) AND (elements.archived = 0)) AND ((elements.enabled = 1) AND (elements_i18n.enabled = 1) AND (entries.postDate <= '2016-05-17 14:08:35') AND ((entries.expiryDate is null) OR (entries.expiryDate > '2016-05-17 14:08:35')))) AND (elements_i18n.enabled = 1)) AND ((target_matrixblocks1.ownerId=:target_matrixblocks1ownerId1) AND (target_matrixblocks1.fieldId = 15))
GROUP BY `elements`.`id`
ORDER BY `sortOrder`. Bound with :locale='en_us', :target_matrixblocks1ownerId1='6'


texts:
I've got a Craft plugin that returns some results based on filter options on the front end. The filter sends an ajax submissions and returns the markup to populate the front end with.

I've read the docs on CSRF protection and specifically implemented what it says for jQuery based post submissions. However I'm still getting a 400 error saying "Bad Request - The CSRF token could not be verified." for every post request.

You can see a token is being sent in the post data.


texts: Craft - suitability for membership/user registration and document upload/management

texts:
I have created about 30 sites using Perch but find it somewhat frustrating, especially the support. Considering using Craft for my next project but can it handle:
Membership/user registration. Ie can i restrict certain sections of the iste to registered individuals or members?
Document management. The prospective client I am tinhking of using for my first Craft site also holds lots (~100) of mainly PDFs some for public use and others for members only. They need a fairly simnple way for the end usuer to be able to upload an keep them oraganised.

Would Craft satisfy these criteria?

Cheers - Mark


texts:
I have a simple question about Assets. I want to output some HTML around a set of image IF there is more than one image. If there is just one image I would output different HTML. I know how to do this easily within EE's Assets but not sure how to do it in Craft's Assets.

In EE I would use something like:

{if photo:total_files > "1"}

{if:else}

{/if}

I think I could target the first image but not sure how to construct the full conditional.

{% if entry.photos | length %}

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

{% endif %}


texts: How can I route a specific entry in a structure section to its own template?

texts:
While setting up a site recently I wanted to route a specific entry in a structure section to its own custom template. Using a dynamic route sounded like the right option until I remembered that it wouldn't work due to Craft's routing order (matched entry uri comes before matched template).

I considered adding a conditional redirect to the structure's generic template but this feels a bit dirty. Does anyone have a better solution of how to make this work?


texts: How can I merge a Modified Date and Time in Twig?

texts:
I am trying to generate a modified date and time from a combination of content fields and the current date but I am getting stuck and keep hitting errors, so my logic is either not correct or  I am approaching this all wrong. Here is an explanation with some examples of what I am trying to achieve.
So I want to check if a child that is registered to a class (A class occurs on a specific day/time each week) that they only get to see a page if the date and time of their class is now in the past. As an example, a child is on a class Tuesday 4.15pm - 5.15pm - I want to ensure they only get to see the page at 4.15pm.
In the CMS I have a select list for the day, and related entries for the time slots, but these use standard time fields.
Here is how I have tried to approach it.
###First Generate a Modified Date based on the their class day. This will check if Tuesday is this week or next week. Like so:

#Get the class day for the child
{% set classDay = child.tuitionClass[0].weekday.label %}

#Set the next occurring date for the class day
{% set nextClass = now | date_modify('this ' ~ classDay) %}

This is fine so far and gives me a date to work with. I can compare today's date against the next class date to see if it has passed.
The part I am stuck on is the time aspect. I cannot figure out how to generate the modified_date with the class time so I can do the comparison on one object rather than two.
#Get the class time
{% set classStartTime = child.tuitionClass[0].classTime[0].startTime %}

How can I merge the class time with the modified date so that the nextClass is set to the date AND time of the nextClass. With the logic earlier it sets the time to default to 12:00 - the start of the day.
Everything I try I either hit an error Object of class DateTime could not be converted to string.
I could perhaps as suggested do the logic in two parts. First compare the date and then compare the time. But I was hoping for a single comparison.
Is anyone able to help out with this final part of the logic?
Thanks in advance.