texts:
I have a Craft site with a Client license. After the recent license transition to Solo/Pro, a red banner appears along the top that reads "You’re running Craft Client with a Craft Pro license. [Resolve]." Hitting "resolve" displays the following:

So, if I reinstall as pro, is that a new $299 charge (plus the annual $59)? Will "reinstalling" result in system downtime and/or data loss?


texts:
I'm having trouble making updates using composer on a new CraftCMS 3 install. This was working at one point as I was able to require a local repository for plugin development purposes.

Any composer usage ("composer info", "composer update", "composer list", etc.) yields the following:

[UnexpectedValueException]
Package cebe/markdown's source key should be specified as {"type": ..., "url": ..., "reference": ...}, {"type":"git","url":"https:\/\/github.com\/cebe\/markdown.git","reference":null} given.

My (abbreviated) installed.json is as follows:

[
{
    "name": "cebe/markdown",
    "version": "1.1.2",
    "version_normalized": "1.1.2.0",
    "source": {
        "type": "git",
        "url": "https://github.com/cebe/markdown.git",
        "reference": null
    },
    "dist": {
        "type": "zip",
        "url": "https://api.github.com/repos/cebe/markdown/zipball/",
        "reference": null,
        "shasum": ""
    },
    "require": {
        "lib-pcre": "*",
        "php": ">=5.4.0"
    },
    "require-dev": {
        "cebe/indent": "*",
        "facebook/xhprof": "*@dev",
        "phpunit/phpunit": "4.1.*"
    },
    "time": "2017-07-16 21:13:23",
    "bin": [
        "bin/markdown"
    ],
    "type": "library",
    "extra": {
        "branch-alias": {
            "dev-master": "1.1.x-dev"
        }
    },
    "installation-source": "dist",
    "autoload": {
        "psr-4": {
            "cebe\\markdown\\": ""
        }
    },
    "notification-url": "https://packagist.org/downloads/",
    "license": [
        "MIT"
    ],
    "authors": [
        {
            "name": "Carsten Brandt",
            "email": "mail@cebe.cc",
            "homepage": "http://cebe.cc/",
            "role": "Creator"
        }
    ],
    "description": "A super fast, highly extensible markdown parser for PHP",
    "homepage": "https://github.com/cebe/markdown#readme",
    "keywords": [
        "extensible",
        "fast",
        "gfm",
        "markdown",
        "markdown-extra"
    ]
}

]

I've been staring at this all afternoon and could use a fresh set of eyes. Anyone have any ideas?

Thanks in advance.


texts: Paginate Import with Google Sheets & Feed Me

texts:
It's great that Feed Me accepts a Google Sheets API URL as the feed URL, like
https://sheets.googleapis.com/v4/spreadsheets/xxxxxxxxxxxxxxxx/values/SheetName?key=xxxxxxxxxxxxxxxx

But is it possible to paginate the rows using this option?
I currently have several hundred rows in my spreadsheet. I don't see anymore information in the docs other than how to set up your feed URL.


texts: Craft Migration fails (SuperTable propagationMethod)

texts:
I'm trying to upgrade Craft from 3.3.1.1 and I'm getting an error. I am updating via Composer and get the following error when I run the migration script after upgrading:

Unknown Property: Setting unknown property: verbb\supertable\fields\SuperTableField::propagationMethod

Migration: craft\migrations\m190913_152146_update_preview_targets

I received a similar error when I tried to run the save entries script from the CLI as recommended in the upgrade documentation.

- Resaving test (10554) ... error: Setting unknown property: verbb\supertable\fields\SuperTableField::propagationMethod

I'm running the upgrade on my local server via Valet. Restoring the database brings me back to the migration screen...

Any suggestions would be helpful.


texts: Customer details revealed at base order URL

texts:
If anyone visits http://site.com/commerce/customer/order they see the last order made even if they are not logged in and not related to that order in any way.

The customer can see their order info if they use http://site.com/commerce/customer/order?randomcustomerorderstringforthatspecificorder. Stripping the ? and the random string after it shows the last order.

I am using the standard template to display order information. They are redirected to this page after they complete a transaction. Relevant code is:

{% extends '_layout' %}
{% set number = craft.request.param('number') %}
{% set order = craft.commerce.orders.number(number).first() %}
{% if not order %}
    {% redirect 'commerce/customer' %}
{% endif %}

So it does not seem to be redirecting to commerce/customer.

Any help would be great.


texts: February always comes out as March - expect /yyyy/mm to be 2018/02 but it's 2018/03

texts:
This is a site that was recently updated from Craft 2 to Craft 3 and before the update this issue did not occur.

Here is the code:

{# all entries sorted by year/month #}
 {% set allEntries = craft.entries.section('photoblog').limit(null).orderBy('postDate desc').all() %}

    {% for year, entriesInYear in allEntries | group("postDate|date('Y')") %}

{{ year }}

          {% for month, entries in entriesInYear | group("postDate|date('F')" ) |  reverse %}

{{ month }}&nbsp;({{ entries|length }})

          {% endfor %}

    {% endfor %}

Everything works correctly except for February which always outputs 03 and not 02 as expected.

If you go to https://sean-smith.net/calendar and hover over any February link you'll see that the link is set to March inexplicably.


texts: .htaccess trailing slashes and ajax calls

texts:
I'm building something with Craft and Vue.js and realized that I could view my page with or without a trailing slash, but when it had a trailing slash, my ajax calls to the Element API endpoint failed, thus the content wouldn't load.  So I've changed all my endpoints to not include the .json like in the plugin's docs examples and just end in a /.

I'm not sure if it's better or worse to force a trailing slash (I've read arguments for either way online), but I figure it's best to just choose one and go with it, so I've chosen to force it, but then I can't log into my admin control panel anymore, and I get some javascript errors elsewhere on front-end pages.

Here's my .htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Redirect non www to www
    RewriteCond %{HTTP_HOST} ^website.com
    RewriteRule (.*) http://www.website.com/$1 [R=301,L]

    # 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]
</IfModule>

I'm also adding 'addTrailingSlashesToUrls' => true, in my config file.

How can I fix this to have trailing slashes, ensure that ajax calls don't fail, and still log into the cms?  Or should I just force no trailing slash?


texts: Can't access Craft CMS admin in Chrome Canary 63.0.3233.0

texts:
I'm not able to login to my local craft cms in google chrome canary, version 63.0.3233.0. I've attached a screenshot of the error message I've received when trying to go to the standard login page. I can log in fine on normal Chrome.

I know Canary is beta software of newer version of chrome, however, if they release this into the wild later on, is it something to worry about? I'm running MAMP free. Is it something that can be fixed with MAMP pro or? Any suggestions most welcome. Thanks :)


texts: Using renderTemplate for a plain text twig template

texts:
Is there a suitable way to use renderTemplate or another method to output a twig template that is plain text?

I'm working with a plugin that has an email template for both HTML and plain text, previewing the HTML version is simple, doing the same with the plain text works but the visual preview within Craft shows the content without any of the spacing or line breaks because its rendering as HTML, viewing the source the correct output with the line breaks and spacing etc is shown. I was wondering if there was a way to output the plain text template in a similar way.


texts: Get a field's required attribute in frontend form

texts:
I am trying to get the required attribute of a field in a frontend form. I know this attribute only makes sense in the context of an entry type. Doing this

craft.fields.getFieldByHandle('handle')

returns a FieldModel object which has no context to any entry type. This way I can get the field name and the instructions for example. In Craft we set the required attribute in the entry type editor. So my question is:

How can I get a field's required attribute in the context of a specific entry type?

Edit: My goal is to create a frontend form of an entry type and have every change to the field's required flags in the backend automatically reflected in the frontend form: <input required ...>.


texts: Front end profile does not save data - form action

texts:
I've been having trouble getting a front-end profile template to save any data.
It was quite complex so I've gone back to a base install of Craft with no custom fields for a User.

Using the example code from the docs it still doesn't save any data.
http://buildwithcraft.com/docs/templating/user-profile-form

This is running the full version of Craft on localhost.

I have a custom route of /profile set to a template called 'profile'.

Loading the page loads all currently stored data exactly the same as the CP.

Submitting the form reloads the page but none of the input data is saved and redisplayed. Going to the CP also shows nothing was saved.

After a few hours of trouble-shooting I discovered, on submit from the front-end template, the saveUser method was not running. It was from the CP.

Adding action="{{ siteUrl }}" to the form gets it working. But oddly then introduces the front controller in to the URL after submit, eg. http://localhost/index.php/profile.

There's no mention in the example code of a form requiring an action value. I can't work out why the example code doesn't work or why I need action. I'd rather not have the pretty URLs messed up.

Help?

Profile

<form action="{{ siteUrl }}" method="post" accept-charset="UTF-8" enctype="multipart/form-data">

    {{ getCsrfInput() }}

    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="profile">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">

    <fieldset>
        <legend class="visually-hidden">Personal details</legend>

        First name *
        <input id="firstName" type="text" name="firstName" value="{{ currentUser.firstName }}" placeholder="Jane" required="required" aria-required="true" autofocus="autofocus">

   </fieldset>

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

Update 10-08-2015

The profile form submitting seems to be a red-herring. When installing Craft I couldn't get it to work with clean URLs so I edited Apache's config to set 404s to redirect to crafts index.php. I'd since forgot. Local config:

Mac OS X 10.10.4
MAMP (not pro)

By default MAMP has AllowOverride None. That was stopping the .htaccess file from working. I'm using vhosts so I've manually set this in the vhost config. Another gotcha is Crafts config of omitScriptNameInUrls and usePathInfo. Craft caches test results for 24 hours, so I had to clear the cache before my updated vhost config worked.

<Directory "/path/to/craft/public">
    Options FollowSymLinks
    AllowOverride All
    Order Allow,Deny
    Allow From All
</Directory>

The title of this SE question is all wrong now but it's valuable info. OK to change? I'd also say this is a common enough set-up to be in the official docs?


texts: How to change an entry's slug on EVENT_AFTER_SAVE_ELEMENT?

texts:
My entries' titles are auto-generated from several fields values on first save.

When one of these fields values change, I would like to update the auto-generated slug also:

Event::on(
    \craft\services\Elements::class,
    \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT,
    function (Event $event) {
        $entry = Entry::find()
            ->id($event->element->id)
            ->one();

        if ([] !== $entry) {
            $title = craft\helpers\StringHelper::toAscii($entry->id.'-'.$entry->title);
            $title = craft\helpers\StringHelper::toLowerCase($title);
            $title = str_replace(' ', '-', $title);

            //  I tried this below, but none works
            $entry->slug = $title; // ⬅ Not working
            $entry->setFieldValue('slug', $title); // ⬅ Error
            Craft::$app->elements->saveElement($entry); // ⬅ Infinite loop
            $event->element->slug = $event->element->id; // ⬅ Not working
        }
    }
);

Unfortunately, none of these methods works. Any idea how to achieve this?


texts: Get a named parameter value from request

texts:
Yii's named parameters are available in the template. For example, for the following route configuration:

'post/<post_id:\d+>' => ['template' => 'post-entry'],

The value of post_id in my template for the request post/3 will be 3.

But how can I access it from PHP, for example from the Craft::app -> getRequest() ?

Note: I don't mean queryString parameters. QueryString parameters can be accessed using getParam('paramName').


texts:
How to fetch Elements with a complex DB query?
E.g. with some nested AND/OR conditions or just apply two conditions to one field?

For example my Elements have a field eventDate. I want to fetch all Elements where eventDate is NULL or equals "1900-01-01".

The standard way to build Element Criteria is:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->eventDate = '=...';
$models = $criteria->find();

It doesn't provide an ability to apply several conditions for same field. Is it possible at all without assembling huge queries manually?


texts:
I have a category that I'm trying to load via a plugin. Looking at the categories service I see there is a function called "getCategoryById" but I don't know what the ID is so instead I'm loading the category group thinking that the ID provided there is what I need, apparently it is not.

Kinda of stumped on this one. Any advice?

Thanks,


texts:
Are there any tax plugins available for some of the major sales tax API services (i.e. TaxJar, Taxamo, Avalara)?

Are there any shipping plugins available for some of the major shipping services (i.e. UPS, FedEx)?

The reason for my questions is that it would seem that the Craft Commerce plugin is extremely limited in those 2 areas.


texts: Nested objects containing array in the Elements API plugin

texts:
I have an object look which contains an object categories from type of array. Currently I have to do the following to display the categories proper in the response.

'endpoints' => [
        'looks.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'looks'],
            'transformer' => function(EntryModel $entry) {

                // Create an array of all the photo URLs
                $categories = [];
                foreach ($entry->categories as $category) {
                    $object = (object) ['id' => $category->id, 'title' => $category->title];
                    $categories[] = $object;
                }
                return [
                    'title' => $entry->title,
                    'id' => $entry->id,
                    'categories' => $categories
                ];
            },
        ]
    ]

Is there a more elegant way to doing this? Especially because I'll have a lot of more cases where I have to deal with arrays in objects and arrays in objects and so on.

A structure could looks something like this

[
    {
      name: "ads"
      categories: [
         {
            name: "asdasda"
            subCategories: [
                name: "asdasdsa"
           ]
          }
      ]
    }
]


texts: Pro licence error - Craft is unable to purchase an edition upgrade at this time

texts:
I'm trying to purchase a pro license for Craft 2. The site was on a staging server which is now uploaded to the live server. At first, there were 2 warning messages. First saying running Craft Pro on Solo license. And another saying you are using a license belonging to the staging site.

I removed the license .key from the config folder and cleared the cache and this re-created the license and cleared the staging site message. However, when I go to purchase a pro license it goes through the fields and ends with a message.

Craft is unable to purchase an edition upgrade at this time.

Does anyone have any idea what is going on and how to resolve this? The site needs to go live today.

Cheers


texts: How can I output the Field Name in my template?

texts:
I've created a plain text-field and added this field into a section.
I then created an entry and filled it with content.

I know I can output the content of the field in my template with {{ entry.field_handle }}, but is it also possible to display the field name? If so, how?


texts:
I need to filter a sections entries by more than one category but only return entries that belong to all category id's passed in a URL parameter.

Now I can get the correct output if the id's are hard coded but not if contained in the URL parameter.

URL: ajax-swatches?cats=171,172,179

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

{% set swatches = craft.entries({
    section: 'swatches',
    relatedTo: ['and',catPars]
}) %}

I presume the 'relatedTo' section is treating the 'catPars' variable as a single entry and ignoring the ',' and next values?

Any help would be really appreciated :)


texts: Programmatically add entries to an Entry field (craft\fields\Entries)

texts:
I work with Craft 3.

I have an Entries field in a global set, I am able to get the global set, and then "read" this field programmatically (in a plugin) to fetch the entries that where added to it by looping on the EntryQuery data.

I want to be able to add another entry to this field via a php function in my plugin (so not in a Twig template), and then save the it, in the global set. The documentation is not very concrete on this part.
Thanks

here is my code :

            $reglages = \craft\elements\GlobalSet::find()
            ->handle('reglages')
            ->one();

            $entries = [$entry->id];

            foreach($reglages->curatedHomepageArticles as $tmpEntry)  {
                $entries[] = $tmpEntry->id;
            }
            $entries = array_unique($entries);
            $entries = array_slice($entries, 0, 10);

            $reglages->curatedHomepageArticles = $entries;

            $return = Craft::$app->getGlobals()->saveSet($reglages);
            var_dump($return);

The point is to add the $entry to the entry field called curatedHomepageArticles with no duplicates. I am able to read the entries that are already in the entry field, and then build the array of ids called $entries but nothing happens when I try to update the field with a new list of entries id $entries. $return is true and there are no exceptions thrown. Can you help me understand what is going on here ?


texts:
I have the 404 page setup as a single in sections under page404.

I have a postImage field that pulls images from assets.  It is assigned to the page404 field layout and it is assigned in the entry.

I tried the this template approach:

{% set notFound = craft.entries.section('page404') %}
<img src="{{ notFound.postImage.first().url }}" width="800" height="800" alt="">

but I keep getting the following error:

  Impossible to access an attribute ("url") on a null variable

What am I doing wrong, and how should it be template?


texts: Canonical url for product with multiple categories

texts:
I'm building a shop using Craft Commerce where a single product can be assigned to multiple categories. The url structure I'm using for the product detail page is: http://domain.com/category/product-url

In an effort to avoid being penalised for duplicate content I would like to set the canonical URL for my product detail page by always pulling the first category as the canonical URL in the meta. I've tried a few things but keep getting stuck - any tips ?


texts: conditional does not run first in a file that is included using the extends feature for twig

texts:
I have this conditional included in a layout file I use within others, using the extends feature in twig.

This is at the very top of _layouts/application.twig

{% if not currentUser %}
    {% redirect "login" %}
{% endif %}

I have this at the very top of account/index.twig

{% extends "_layouts/application" %}
{% set name = currentUser.getFullName() %}

If the user is not logged in, I expect it to redirect the user to the login page, as it contains the if not currentUser conditional at the very beginning of the extends file: _layouts/application.twig

I then copied and pasted the if not currentUser code and placed it above the extends call within the account/index.twig file (like seen below):

{% if not currentUser %}
    {% redirect "login" %}
{% endif %}

{% extends "_layouts/application" %}

and it works as I expect it to.

Why does it not work with the if conditional being included in _layouts/application.twig file that I include by using {% extends "_layouts/application" %}


texts:
Apologies if this has come up before. I did check but the previous post referred to version 2.x and was regarding a bug.

I have set up 2 image transforms for images but nothing works. The assets folder is writable. Files upload without issues and I can crop them, rotate them, etc. but Image Transforms don't work.

Anyone know what the issue could be?


texts: Cart completed at gateway redirect issue

texts:
Recently I've found that when a customer goes to checkout and hits the craft\commerce\controllers actionPay() using a custom gateway that it's automatically marking the cart as complete.

This never used to happen, the gateway would set the cart to complete after receiving a webhook response itself at a later time, allowing the customer to go back and update their cart before checking out properly(or not as they decide).

Now if they hit the back button they, obviously, have an empty cart as it's been marked as completed (along with the automated emails etc that are sent at that time).

Can someone point me in the right direction on how to stop this auto-complete from happening?


texts: Is there a JavaScript event that is triggered when a field type's settings html is displayed within Matrix?

texts:
Google Maps for Craft has a settings page that uses JavaScript that aids the user in setting up their Google Maps field. So the user can set a default center and zoom for the map, and they do this by manipulating a map in the settings page. All works fine when creating a standard field. I used the $(document).ready() method to trigger my code, but since Matrix creates these fields after the DOM has already triggered that event, my code isn't getting instantiated. Matrix for EE has a similar callback function that is triggered, so I assume Matrix for Craft has the same thing.

Any code examples for listening for when new Matrix fields are created? I tried browsing through the existing field type code and MatrixConfigurator.js but couldn't find any examples yet.


texts: Can you run two different Stripe accounts as two different gateways in Craft Commerce?

texts:
Does anyone know if there are any drawbacks/gotchas to having multiple Stripe gateways setup in commerce for Craft Subs?

If I wanted to have two sites on my craft install and for them to both use Commerce Subs, but for each site to have it's own Stripe account (i.e 2 stripe gateways with different API details in both)

Would that work ok with stripe callbacks etc etc etc?


texts: List out all "Layout Tabs" in the frontend

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

Services

Testimonials

Gallery

Thanks :)


texts: Save the form if not complete and come back another time to complete the form

texts:
I am using the FormBuilder plugin and I want users to be able to fill in a form. If they abandon the form without completing it or submitting it, I want the form to be saved and when they login and return to the form I want the user to be able to continue where they left off.

I am fairly new to Craft CMS and Twig so I don't know where to start with this or if this is even possible in Craft.

Thanks in advance!


texts: Multi locale, multi-domain Live Preview failing

texts:
I have a multi-locale site set up with the different locales in different domains

phoseon.craft.dev - English site
phoseon.it.craft.dev - Italian site

etc.

I am having problems getting Live Preview to work with a locale other than English.

The page I am trying to get this to work on, test-single, is a single, with a template that just displays the title (so no complexity there).

When I try to use Live Preview in a locale other than English, I get this error in the console:

  Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://phoseon.it.craft.dev/. This can be fixed by moving the resource to the same domain or enabling CORS.

And no Live Preview, just a white screen.

Based on this answer I added this to .htaccess for http://phoseon.it.craft.dev

Header add Access-Control-Allow-Origin "http://phoseon.craft.dev"

And now I see these requests, and still a white screen for the Live Preview:

POST http://phoseon.it/craft.dev/test-single 302 Found
  Request Headers:
    Accept  */*
    Accept-Encoding gzip, deflate
    Accept-Language en-US,en;q=0.5
    Content-Length  198
    Content-Type  application/x-www-form-urlencoded; charset=UTF-8
    Host  phoseon.it.craft.dev
    Origin  http://phoseon.craft.dev
    Referer http://phoseon.craft.dev/admin/entries/testSingle/1742-testsingle/it_it
    User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:35.0) Gecko/20100101 Firefox/35.0
  Response Headers:
    Access-Control-Allow-Orig...  http://phoseon.craft.dev
    Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Connection  Keep-Alive
    Content-Encoding  gzip
    Content-Length  2346
    Content-Type  text/html
    Date  Mon, 16 Feb 2015 20:38:14 GMT
    Expires Thu, 19 Nov 1981 08:52:00 GMT
    Keep-Alive  timeout=5, max=100
    Location  http://phoseon.it.craft.dev/login
    Pragma  no-cache
    Server  Apache/2.2.26 (Unix) DAV/2 PHP/5.4.30 mod_ssl/2.2.26 OpenSSL/0.9.8zc
    Set-Cookie  CraftSessionId=gtm75r2a9it49820uueam9hpe2; path=/; HttpOnly
    Vary  User-Agent,Accept-Encoding
    X-Powered-By  PHP/5.4.30

  And the response is the site's 404 page

GET http://phoseon.it.craft.dev/login 404 Not Found
  Request Headers:
    Accept  */*
    Accept-Encoding gzip, deflate
    Accept-Language en-US,en;q=0.5
    Content-Type  application/x-www-form-urlencoded; charset=UTF-8
    Host  phoseon.it.craft.dev
    Origin  http://phoseon.craft.dev
    Referer http://phoseon.craft.dev/admin/entries/testSingle/1742-testsingle/it_it
    User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:35.0) Gecko/20100101 Firefox/35.0
  Response Headers:
    Access-Control-Allow-Orig...  http://phoseon.craft.dev
    Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Connection  close
    Content-Encoding  gzip
    Content-Length  42163
    Content-Type  text/html; charset=utf-8
    Date  Mon, 16 Feb 2015 20:38:14 GMT
    Expires Thu, 19 Nov 1981 08:52:00 GMT
    Pragma  no-cache
    Server  Apache/2.2.26 (Unix) DAV/2 PHP/5.4.30 mod_ssl/2.2.26 OpenSSL/0.9.8zc
    Set-Cookie  CraftSessionId=isldd40afpu41mr9as659f6rs7; path=/; HttpOnly
    Vary  User-Agent,Accept-Encoding
    X-Powered-By  PHP/5.4.30
    charset utf-8

  And the response is agin the site's 404 page

Anyone else encountered this? Know what's going on? Recommended fixes?


texts:
Just upgraded to Craft 3.5+ and now all my non-primary site's pages are not found.
All my english page (primary site is in french) returns a "Template not found".
So "en/anypage" returns a "Template not found" now.
Thanks for your help.


texts:
With SEOmatic I want to be able to dynamically change the type of my mainEntity, which defaults to "Webpage" and in some cases I want to change it to "Event"
In an older project I did this:
{% do seomatic.jsonLd.get('mainEntityOfPage').type('Event') %}

But if I dump the mainEntity again, nothing has changed:
{% dd seomatic.jsonLd.get('mainEntityOfPage') %}

It's still a nystudio107\seomatic\models\jsonld\WebPage#1
How can I achieve this?
I'm using Craft 3.4.30 with Seomatic 3.3.35


texts:
I've this macro:

{{ dh_macros.dh_postNav(entry, 'blog', 'postDate', 'prev article', 'next article') }}

I call it on my blog/_single template and it works for 90% of the posts. But the newest 6 posts doesn't show the next / prev links.

This is the last post how it works fine. In the next newer post it looks like this:

Here is the next post link missing. And one post newer there is no link shown neither next nor prev :/

To appreciation, there are next / prev posts there.

It feels really random and I've no idea what's going wrong.
Maybe someone has an idea.

Thanks!

Here the Full Code maybe someone need it:

{#
    Prev / Next Link
    Examples:

    {{ dh_macros.dh_postNav(entry, 'work', 'postDate', 'prev work', 'next work' ) }}
#}

    {% macro dh_postNav(entry, section, order, prevLabel, nextLabel ) %}

    {# Set vars #}
    {% set section     = section|default('blog') %}
    {% set order       = order|default('postDate') %}
    {% set prevLabel   = prevLabel|default(false) %}
    {% set nextLabel   = nextLabel|default(false) %}

    {# Set parameters for prev/next elements list #}
    {% set data = craft.entries.section(section).order(order).limit(null) %}

    {# Get the prev/next elements #}
    {% set prevEntry = entry.getPrev(data) %}
    {% set nextEntry = entry.getNext(data) %}

    {# And make sure to only output the links if the element exists #}
    {% if prevEntry or nextEntry %}

            {% if prevEntry %}

                        {% if prevLabel != false %}
                            {{ prevLabel }}
                        {% endif %}

                        {{ prevEntry.title }}

            {% endif %}

            {% if nextEntry %}

                        {% if nextLabel != false %}
                            {{ nextLabel }}
                        {% endif %}

                        {{ nextEntry.title }}

            {% endif %}

    {% endif %}

{% endmacro %}


texts:
A couple questions...

1) How do these dynamic searches work? A excellent example is found at McMaster Carr website

2) Is there any search plugin like that for Craft? I did not see any.


texts: Exclude category from channel entries (with pagination)

texts:
I'm trying to paginate a channel of entries but I also need to exclude any entries that relate to a specific category.

This is what I have so far...

{% set insightCategory = craft.categories({"slug": "insights"}).first() %}
{% set insightsEntryIds = craft.entries.section('blogChannel').relatedTo({targetElement: insightCategory}).limit(null).ids() %}

{% paginate craft.entries.section('blogChannel')|without(insightsEntryIds) as entries %}
    {% for blogEntry in entries %}
        <p>{{ blogEntry.title }} ({{ blogEntry.id }})</p>
    {% endfor %}
{% endpaginate %}

Unfortunately the pagination doesn't seem to work with the |without filter. How can I achieve this?

Thanks


texts: How to watch for changes on an Element Select Relations field?

texts:
I have a situation where I'd like to watch for a change in an Element Select field and determine if any Elements have been selected or not.

Element Select fields have two input elements. One, is always present and never changes, and the other gets added and removed from the page depending on if any items have been selected. Here's a simplified version of the HTML:

    {# This input field is always present and never changes #}
    <input type="hidden" name="fields[assets]" value="">

        {# When you add or remove elements, this .element div and input
           get added and removed from the DOM #}

            <input type="hidden" name="fields[assets][]" value="430">

I've tried various listeners but so far they all get destroyed when the second input gets removed from the page, or never get added to the right input field if it is not on the page.

How do I listen for an element that may or may not exist on the page?


texts: Display only one entry with checkbox checked in my pagination loop?

texts:
I have multiple entries in 'blog' that have the 'featurePost' checkbox field checked. I want to display ONLY the latest, but this code is displaying multiple fields.

{% paginate craft.entries({ section: 'blog', order: 'featurePost desc, postDate desc', limit: 5 }) as entriesOnPage %}

{% for entry in entriesOnPage %}
    {% if craft.entries.section('blog').featurePost.limit(1) | length %}

    {% else %}

    {% endif %}
{% endfor %}

{% include "partials/blog/_blog-pagination" %}

{% endpaginate %}


texts: How to make calls to render a fixed asset

texts:
I am trying to call an image in my twig template whose identity is known. Here is my code that does not work

{% set asset = craft.assets.kind('image').folderId('9').filename('fitness-strength-strong-male-1.jpg') %}

{% set thumb = {
    mode: 'crop',
    width: 800,
    height: 600,
    quality: 75,
    position: 'center-center'
} %}

 {% if asset %}
    <img alt="No More Posts" class="img-responsive center-block" src="{{ asset.getUrl(thumb) }}" >
 {% endif %}

This is not working at all. My folderId is correct (got it from craft_assetfolders table) and filename is copied and pasted. Not sure what I am doing wrong.


texts: 500 error: uploading files (duplicate primary key)

texts:
Afternoon all - odd issue where created some new asset folders and adding new files is timing out. If I view the folder in question (on the server) I can see the file has been successfully uploaded but this isn’t reflected in the back-end. Craft 2.4. Console Log is returning a POST /admin/actions/assets/uploadFile 500 (Internal Server Error) response.

Checking the craft logs it is throwing a Duplicate entry '3996' for key 'PRIMARY' error in the craft_assetfiles table. It looks like somewhere between builds/deployments the craft_assetfiles table has got out of sync. I've tried updating the Asset and Search indexes but with no success.

Any thoughts on debugging or resolving?


texts: How to rearrange the order of blocks of a single matrix field using a frontend form?

texts:
I'm trying to rearrange the matrix block order using a frontend form.

If I use JavaScript to change the order of inputs in the DOM will this change the order in the backend after form submission?
How do you include the correct value for image fields, is this using the image id?

I have a reduced test case of what I came up with below, anyone see where I'm going wrong?

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
   {{ getCsrfInput() }}
   <input type="hidden" name="action" value="entries/saveEntry">
   <input type="hidden" name="redirect" value="viewentry/{slug}">
   <input type="hidden" name="entryId" value="{{ entry.id }}">
   <input type="hidden" name="fields[galleryBlock]" />

   {% for block in entry.galleryBlock %}

       {% switch slide.type %}

       {% case 'landscape' %}
            {# block 1 #}
            {% set image = block.image[0] ?? null %}
            <input type="hidden" name="fields[galleryBlock][{{ block.id }}][landscape]" value="{{ image.id }}">
            <input type="hidden" name="fields[galleryBlock][{{ block.id }}][enabled]" value="1">

        {% case 'portrait' %}
            {# block 2 #}
            {% set image = block.image[0] ?? null %}
            <input type="hidden" name="fields[galleryBlock][{{ block.id }}][portrait]" value="{{ image.id }}">
            <input type="hidden" name="fields[galleryBlock][{{ block.id }}][enabled]" value="1">

    {% endswitch %}

{% endfor %}


texts: CSS and JS tags with custom version parameter

texts:
When using {% css '/path/to/file.css' %} craft adds a v= query parameter by itself so that it comes out like this:
<link href="/path/to/file.css?v=1612895916" rel="stylesheet">

I can't find anything in the craft docs about changing this or making it something custom. The docs for css only states that

To register a CSS file, the URL must end in .css.

For various reasons I need to attach a couple of other url parameters to the generated link tag.
I know I could write the link tag myself and use twig in the href but I would like to take advantage of craft de-duplicating if the same css/js file is included multiple times. Likewise going the {{tag('link', {href:....)}} route would also not de-dupe if the tag was added multiple times.
Any idea on how to use a custom set of URL parameters?


texts: Allowing non staff users to access CP to post and edit posts?

texts:
I ask this in the context of a sharing content site, let's say a forum.
This doesn't seem to be a recommended practice, and I wish to know if there is a particular reason:

I plan to let non staff, but registered site visitors to access the CP, to post content in specific allowed categories of my site. Access to the cp is a HUGE time saver: user can post entries, with all the CSS/JS work done, which means that they can benefit from autocomplete tags and all the goodies from the CP. They can see a list of all their entries, edit them etc etc....

Why should I bother doing custom forms if all can be done with CP access ? Any reason ?
I don't believe there is a security concern since the CMS allows very precise control of permissions and what user in a group can do in the CP.


texts:
Can I resolve full URL to some object - entry or category, from inside Twig template?

Mind you, I don't mean searching for something by slug, but by full URL. So, for example, instead of passing 'some-slug' to function, i want to pass 'some-category/some-subcategory/some-slug'.

I need to to this, because i want to create breadcrumbs links based on craft.request.segments object. So, i need to look up for entry object for some-category, then entry for some-category/some-subcategory/ and then for some-category/some-subcategory/some-slug (well, i dont really need last one because its just page im on currently).


texts: Install Zoho CRM SDK (or any SDK for that matter)

texts:
For a client I need to connect a rather complex contact form with the Zoho CRM. They're offering a PHP SDK which sounds great, but I can't get it to work. It's very likely that I'm just stupid, because I can't even include the SDK to just call the initial setup method.

The documentation says (under "Using the PHP SDK") to include the following line where needed:

require ‘vendor/autoload.php’

That doesn't seem to be needed, as it's already done in the main index.php by Craft itself.

I want to use the SDK within a service class I've created under modules/services. So within my class I tried the following:

require "../vendor/zohocrm/php-sdk/src/index.php";

That's getting the the index.php from the SDK but when I'm calling the method ZCRMRestClient::initialize() I just get the following error message:

  Class 'modules\services\ZCRMRestClient' not found

I'm probably missing some really basic stuff but I just don't know what else to do.


texts:
Is there any way to initialize a stdClass?
Code is simple

    $productOrCategory  =   new stdClass();
    $productOrCategory->stockFutureDays = 0;
    $productOrCategory->stockFutureDate = date('ymd');

but im getting Fatal error:  Class 'Craft\stdClass' not found in Controller.php on line 63 and line 63 is the first line i added as code.


texts:
I'm running Craft CMS 3.3.11 on an EC2 machine with Apache and Load Balancer.

After upgrading to Craft 3, I'm having issues with caching.

I use relative paths to resources/assets in my templates (i.e. href="/resources/logo.svg"

After some time, the relative paths in the template are not handled properly - instead of domain name in the URLs I get the server's IP address. It's impossible to fetch data using IP address, so the website is loading forever, the assets won't show up and it logs an error to the dev console:

  Mixed Content: The page at ‘https://example.com/’ was loaded over HTTPS, but requested an insecure image ‘http://172.xx.xx.xx/cpresources/8f9c0f5e/logo.svg?v=1572966078’. This content should also be served over HTTPS.

When I clear caches, everything works properly again.

Adding {{ siteUrl }} before all the relative paths seems to be the easiest fix, but I wonder if maybe I have some configuration issues that should be fixed to prevent this in future?

Server's IP isn't stored neither in the database nor the template files - where does it come from?

Suggestions?

EDIT

Unfortunately it still doesn't work properly.

Here's my code:

                {% endif %}

                {% if craft.rebrand.isIconUploaded() %}

                {% endif %}

For these assets Craft is using server's IP... Can someone please advise?


texts: Render generic message/error template from plugin

texts:
Basically, I'm trying to emulate show_error from EE/CI: http://ellislab.com/codeigniter/user-guide/general/errors.html

I want to just use the generic Craft error template (/craft/app/templates/error.html), like what happens if you have a DB connection error, and have it serve a 500.

This is from with a plugin controller.

What's the best way to do that?


texts:
I want to set up a product filter system based on variants' tags. I encounter two difficulties.

1. Outputting all variants' tags from a group of products.

{% set products = craft.commerce.products.type('Custom').find() %}
{% set variants = craft.commerce.variants.relatedTo(products) %}

{% for pattern in craft.tags.group('patternSwatch').relatedTo(variants) %}
    {{ pattern.name }}
{% endfor %}

{% for pattern in craft.tags.group('patternSwatch').relatedTo(craft.commerce.variants) %}
    {{ pattern.name }}
{% endfor %}

2. Filter product based on the multiple variants' tags

{% set pattern = craft.request.getParam('pattern') %}
{% set tag = craft.tags.group('patternSwatch').title(pattern).first() %}
{% set variants = craft.commerce.variants.relatedTo(tag) %}

{% for v in variants %}
    {{ v.product.slug }}
{% endfor %}


texts: Moving Craft assets from one S3 bucket to another

texts: I have the task of moving a large amount of assets ~50gb from one amazon s3 bucket to another on another AWS account. I've figured out how to copy the files via S3 COPY, but I'm just wondering will it simply be a case of changing the API credentials in Craft to the new bucket? Will this retain all the assets links?


texts: I created a section with the wrong slug. I am now trying to delete the section to start over, or supply a new slug, but I can't do neither. How can I delete this section, or supply a new slug?


texts:
I'm going through my current project and making my loops more "eager". It's working great in several areas and improving performance massively but for some reason I can't get it to work when the entries I'm asking for have a dropdown field. "newsType" is the name of the field. Am I missing some obvious mistake here or are dropdowns a special case somehow?

The error:

Array to string conversion
echo twig_escape_filter($this->env, $this->getAttribute($context["article"], "newsType", array()), "html", null, true);

The code:

{% set latestNews = {
    section : 'news',
    with : ['title', 'body', 'newsType'],
    limit : '6'
} %}

{% if latestNews|length %}
{% for article in craft.entries(latestNews) %}

{{ article.newsType.label }}

{{ article.title }}

           {{ article.body|striptags|slice(0, 150) ~ '...' }}

        Read More &rarr;

{% endfor %}
{% endif %}


texts: Error clearing a field via migration script

texts:
I'm using a migration script to clear out the values for a field on one of my entries. The field is an Entry Field and is not required.

So I do this:

$product->components = [];
Craft::$app->elements->saveElement($product);

But I get this error:

  Argument 1 passed to craft\fields\BaseRelationField::_all() must
  implement interface craft\elements\db\ElementQueryInterface, array
  given, called in
  /var/www/html/vendor/craftcms/cms/src/fields/BaseRelationField.php on
  line 382

I can clear out other fields, even entry fields, just fine. But this particular one gives me this error every time.

I've also tried the following:

$product->components = null;
Craft::$app->elements->saveElement($product);

And:

$product->components = false;
Craft::$app->elements->saveElement($product);

Any ideas?


texts:
I have an old php code in the footer of my site like below. Will like to convert that to twig (which I suspect will be cleaner). I don't know a lick of php hence my question here.

<p>
    <?
      $startyear = 2010;
      $currentyear = date("Y");

      if ($startyear == $currentyear)
   {
      echo "&copy; $startyear Site Name. All Rights Reserved\n";

      }
  else
   {
     echo "&copy; $startyear - $currentyear Sitename. All Rights Reserved\n";

    }
      ?>
</p>


texts: I'd like to examine the memory usage per-page on my website using Craft CMS. Is there a configuration option to enable memory logging or to display memory usage at the bottom of the page?


texts: Charge Plugin - Subscribers have access to the Control Panel and any other subscribers personal information

texts:
We bought the Charge Plugin and got it up and running for a subscription service and the website has just gone live.  We just realised any new user (subscriber) has access to all other users details if they know the control panel URL!!

Charge is the only plugin ignoring user permissions in the CP.  With all permissions turned off, Charge is still available in the left hand panel.

Please advise A.S.A.P.

Thanks

Martin


texts: Redirecting with http status code doesn't render template

texts:
TL;DR

Is there a way to redirect with a status code and have the correct template load with the correct status code?

I have template code which looks like this:

{% if slug is defined %}
 {% set entry = craft.entries.section('foobar').slug(slug).first() %}
 {% if not entry.editable %}
    {% redirect 403 %}
 {% endif %}
{% endif %}

This works fine and redirects to the 403 template, but the problem is that is just redirects (changes the url) to /403 with a status code of 302

So I followed from this question and used the second parameter to set the status code like so:

{% redirect 403 403 %}

Which sets the status code fine but now my 403 template doesn't load. If I try it with 404 the same problem applies.

When I go to a 404 page which is handled by Craft (no redirect tag) then the status code is set correctly and my 404 template loads just fine.

Is there a way to redirect with a status code and have the correct template load with the correct status code?


texts:
I have a Matrix field named -> certificado

with block -> certificados

and fields -> nomeDoCurso, curso, certificado

My Matrix block has no entries but is associated with a user.

How can I fetch the content of the Matrix block for a particular user in the frontend?

I'm trying with:

{% for item in currentUser.certificado %}
    {{ dump(item) }}
{% endfor %}

But this is wrong.

How can I do it?


texts:
I have a plugin, which is using another plugin. The issue is that, I am calling some other plugin information in the init function, and I do receive sometimes this error:

2018-11-07 11:44:57 [-][-][k91hcavi6st542afnhsvhdp61u][error][yii\base\ErrorException:8] yii\base\ErrorException: Trying to get property 'mobileDetectService' of non-object in /home/forge/plugins/releases/20181106223004/src/services/CacheService.php:193
Stack trace:
#0 /home/forge/new.trendsideas.com/releases/20181106223038/vendor/craftcms/cms/src/web/ErrorHandler.php(76): yii\base\ErrorHandler->handleError(8, 'Trying to get p...', '/home/forge/plu...', 193)
#1 /home/forge/plugins/releases/20181106223004/src/services/CacheService.php(193): craft\web\ErrorHandler->handleError(8, 'Trying to get p...', '/home/forge/plu...', 193, Array)
#2 /home/forge/plugins/releases/20181106223004/src/services/CacheService.php(126): trendspublishing\craftplugin\services\CacheService->_generateUri('/hubs/bathroom')
#3 /home/forge/plugins/releases/20181106223004/src/Plugin.php(90): trendspublishing\craftplugin\services\CacheService->uriToFilePath('/hubs/bathroom')
#4 /home/forge/new.trendsideas.com/releases/20181106223038/vendor/yiisoft/yii2/base/BaseObject.php(109): trendspublishing\craftplugin\Plugin->init()
#5 /home/forge/new.trendsideas.com/releases/20181106223038/vendor/yiisoft/yii2/base/Module.php(158): yii\base\BaseObject->__construct(Array)
#6 /home/forge/new.trendsideas.com/releases/20181106223038/vendor/craftcms/cms/src/base/Plugin.php(113): yii\base\Module->__construct('craftplugin', Object(craft\web\Application), Array)
#7 [internal function]: craft\base\Plugin->__construct('craftplugin', Object(craft\web\Application), Array)

This is the error in question:

$mobile_detect = MobileDetect::$plugin->mobileDetectService;

I am not able to replicate it, sometimes a simple database reload is helping sometimes not. So that's why I am only guessing, because I do invoke this call from the plugin init function, that's why the other plugin is not ready yet...
Any thought, best practice on this one?


texts: Redirect on front end Password Redirect not working

texts:
Craft 2.6.2963

I've got a password reset form on the front end which works correctly sending the email. However it doesn't redirect on submit, unless you are loggedin.

redirect works if logged in, but if I'm logged in I wouldn't be resetting my password. How to get the redirect working correctly?

This is my entire form:

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="users/sendPasswordResetEmail">
    <input type="hidden" name="redirect" value="/password-reset-notice">

Username or email

        Email Address
        <input class="form__field form-control" type="text" name="loginName" id="loginName" placeholder="Email Address" value="{% if loginName is defined %}{{ loginName }}{% else %}{{ craft.session.rememberedUsername }}{% endif %}"/>

    {% if errors is defined %}

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}

        <input type="text" name="comment" tabindex="-1" class="form__field form__field--comment" />
        <button class="form__submit button button--lg" type="submit">Submit ›</button>

</form>


texts: Can user group permissions be used to override entry section locale settings?

texts: I have created a localized site with 9 locales for a client in craft v2.6. They are now requesting us to create a user group for each locale so they can assign editors for each of those regions. When a user creates a new entry they want the new entry to be enabled only for the preferred locale for that user instead of the default enabled locales that are set in the section setting. Is it possible to override a section’s settings based on user group permissions? I know this is a strange request and I don't believe it is doable but wanted to see if anyone had any thoughts on this.


texts: How to set multiple 'active' classes from query string

texts:
I'm outputting all tags that are in use and then allowing the user to click these build up a query string to filter and display the results. It's all working fine.

Except, I'm having difficulty understanding what can I use to set an 'active' class on all the selected tags that are being added to the query string.

Setting 1 tag as active is simple enough, but when multiple are selected, I'm not so sure.

The URL looks like this: domain.com/learning/resources?tags=Video+Maths

Setting tags via getParam:

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

Listing all tags in use like this:

{% set resourceTags = craft.entries.section('resources').limit(null) %}
{% for tag in craft.tags.relatedTo(resourceTags) %}

Outputting results like this:

{% craft.entries.section('resources').limit(craft.config.paginateLimit).search(tags) as entries %}`


texts:
How can I make related entries and globals part of the search considerations?
So I have a website search bar that searches the whole website.
Within some jobs pages there are some global elements that exist, a related entries to pull through some on page related content (a call out bar) and some general text that is used on all jobs pages. The reason these are global, is that they can be updated and applied to multiple pages in one go.

However, doing a search for the phrase 'benefits' does not include any jobs pages at all, even though the call-out bar and the global benefits content are used on each job page/template.

Equally on other pages, there is a related module type that links to related entries ((call out bars) and I would like these to be part of the search considerations too, so this issue stretches further than just one section.

Any thoughts on how to achieve this?


texts:
I'm in the process of setting up a shop with Craft Commerce but I'm having some trouble organising the data structure of the products. The problem is that some products have both sizing and color options but I'm not sure how to enter these in the back-end. The most obvious way of doing this would be to make a product variant for each possible combination, like so:

Variant 1: color 1 - size 1
Variant 2: color 2 - size 1
Variant 3: color 1 - size 2
Variant 4: color 2 - size 2

I guess this would work but there will be a lot of variants. And if another one or two options are added in the future the amount of variants will grow exponentially.

Any insight on this would be much appreciated, thanks!


texts: Copy Live to a Test site on same domain?

texts:
I have copied my Craft 2.6 live site directory, and created a test directory on our webserver in an effort to create a test site. Also duplicated the db and changed the configure files to point to the new database.

I am having an issue where the following error appears on the test site:
Internal Server Error file_get_contents(http://closure-compiler.appspot.com/compile): failed to open stream: Redirection limit reached, aborting .

I disabled all plugins on the test site and enabled them one at a time, and found that the COMPRESSOR 1.0 was causing the issue. If I disable COMPRESSOR 1.0 the error disappears, but the test site doesn't look great.  I noticed also that when I disabled this plugin in the test site admin that it also disabled it on my live site.

Other then the general.php & db.php files in the /config folder is there something else that I need to configure?


texts:
I'm building a plugin which creates a few tables, and need to store some fairly robust data. I've done this before and previously gotten by with mostly AttributeType::String and AttributeType::Mixed, but this time I'd like to ensure I'm doing things by the book. Problem is: so far as I can tell, nobody's written the book.

I started out by Model and Record documentation, but they don't reference the possible AttributeType options. Next I read the class reference, but this isn't helpful either. Then I looked at the ModelHelper and DbHelper code. These were a bit helpful, but they don't explain how exactly an AttributeType affects throughout Craft. Eventually I found Experience's Definitive Guide to Validation in Craft series (specifically the linked AttributeType entry). This is quite helpful, but because it's focused mostly on validation, it doesn't answer many of my questions.

It's possible that the book by Experience answers gives more detail, but I'm surprised I need a book to learn about this. It also seems like a slight gamble, as I'm only potentially interested in one chapter right now.

Here's the sort of thing I'm hoping to learn:

What is the Name type used for?
What's the difference between Handle and Slug? Why choose one over the other?
What exactly does Template do, and why does it need its own type?
What's the difference between Url and Uri? Is it just the validation?

Maybe it's not important to know these things, but I think it would be helpful to understand what I'm doing and how these types are processed and affect the system. It's also not completely clear what types are available, as the ModelHelper source doesn't list types like String. I assume that's getting inherited from Yii, but I'm not certain.

Question:
Is there some documentation, or blog post, out there that explains the types available through AttributeType?


texts: One large plugin vs multiple smaller plugins

texts:
I'm finding that occasionally (especially on larger sites), there are little bits of functionality that I need that Craft doesn't offer out of the box. The functionality is usually simple and relatively specific, so I find myself quickly writing little plugins that do the job. Currently I've been creating separate plugins for each bit of functionality I need which can result in some sites having upwards of 5 or 6 small plugins, along with any other plugins that I might be using.

This led me to wonder, when it comes to keeping our Craft installs running as cleanly and efficiently as possible, which is better:

a. Having one large plugin that does multiple different, likely unrelated, things.

b. Having multiple smaller plugins, each doing their own thing.

From a development standpoint I find that having separate plugins makes life easier because everything is more organised, but is this having an impact on Crafts performance?


texts: Are there coding standards I can follow when writing my Craft plugin?

texts:
I eventually figured out that I could use a code sniffer in Sublime Text, load up a CodeIgniter rule set (not a Craft project, obviously), and see in real time where my formatting, spacing and naming conventions could be improved for consistency.

Is there an equivalent standard for Craft/Yii? I'd like to start forming good habits, and the Sublime Text part is a bonus but not required—I'm most interested in whatever standards there are to reference.


texts: Running any query in GraphQL explorer gives error

texts:
In Craft 3.5.17.1 when trying to run any query in the GraphQL explorer it returns this error:
{
  "errors": [
    {
      "message": "Trying to get property 'handle' of non-object"
    }
  ]
}

The console log error that accompanies this is:
Uncaught (in promise) Error: Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: undefined
    at r (graphiql.js?v=1611206975:1)
    at m (graphiql.js?v=1611206975:46)
    at graphiql.js?v=1611206975:46

We have the api route set for GraphQL. We have tried multiple schemas including the fullschema. When opening the Docs section of the Explorer no schema will load. Is this a bug or a setup issue possibly?


texts: Allow uploading of asset with same name as existing asset

texts:
I have an upload form working in my templates (on the frontend), however if I try to upload a file with the same name as an existing asset the file isn't uploaded.

I notice instead a prompt message comes back.

1) I'm not sure how to deal with this, I presume some AJAX call is required.

2) I would prefer it if I could send a value which tells Craft to keep both files without prompting.

What would be the best way of handling this?

The code I've tried is below, using jquery fileupload.

var url = '/actions/assets/uploadFile',
    uploadButton = $('<button/>')
        .addClass('btn btn-primary')
        .prop('disabled', true)
        .text('Processing...')
        .on('click', function () {
            var $this = $(this),
                data = $this.data();
            $this
                .off('click')
                .text('Abort')
                .on('click', function () {
                    $this.remove();
                    data.abort();
                });
            data.submit().always(function () {
                $this.remove();
            });
        });

$('#images-upload').fileupload({
    url: url,
    dataType: 'json',
    formData: [
        { name: 'folderId', value: 1 }
    ],
    autoUpload: true,
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    maxFileSize: 7000000, // 7 MB
    // Enable image resizing, except for Android and Opera,
    // which actually support image resizing, but fail to
    // send Blob objects via XHR requests:
    disableImageResize: /Android(?!.*Chrome)|Opera/
        .test(window.navigator.userAgent),
    previewMaxWidth: 100,
    previewMaxHeight: 100,
    previewCrop: true,

})

And also

    window.csrfTokenName = "{{ craft.config.get('csrfTokenName') }}";
    window.csrfTokenValue = "{{ craft.request.getCsrfToken }}";

var url = '/actions/assets/expressUpload',
    uploadButton = $('<button/>')
        .addClass('btn btn-primary')
        .prop('disabled', true)
        .text('Processing...')
        .on('click', function () {
            var $this = $(this),
                data = $this.data();
            $this
                .off('click')
                .text('Abort')
                .on('click', function () {
                    $this.remove();
                    data.abort();
                });
            data.submit().always(function () {
                $this.remove();
            });
        });

$('#images-upload').fileupload({
    url: url,
    dataType: 'json',
    formData: [
        { name: 'elementId', value: $('input[name=entryId]').val() },
        { name: 'fieldId', value: 8 },
        { name: window.csrfTokenName, value: window.csrfTokenValue }
    ],
    autoUpload: true,
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    maxFileSize: 7000000, // 7 MB
    // Enable image resizing, except for Android and Opera,
    // which actually support image resizing, but fail to
    // send Blob objects via XHR requests:
    disableImageResize: /Android(?!.*Chrome)|Opera/
        .test(window.navigator.userAgent),
    previewMaxWidth: 100,
    previewMaxHeight: 100,
    previewCrop: true,

})


texts:
I am new to Craft and I am trying to figure out how routing works. When I click on an entries nav item, it makes a request to:

.com/index.php?p=admin/actions/elementIndex/getElements

The url of the item is .com/entries/affiliates and the call is ajax.

There is a section called affiliates, but the 'template' field is Null. I can't seem to figure out where the response is coming from.


texts: Send e-mail notificacion ( including attached files ) after user send information with Guest Entries

texts:
I´m using Guest Entries to add to db some info filled by users, including some attach files. Everything works great.

But now i have to send an email with all the info and files that user send, i´m already using Postmaster plugin to send a notificacion, it works, but it doesn´t send the attached files ( i mean, i don´t know how to do it ).

Is there a way to do this with the plugin or another way?

Thanks for your help.


texts:
Caching is hard.

I want to delete the cache when a news entry hits it's expiryDate. So I wrote

{% set newsExpiration = craft.entries.section('news').first()%}

{% cache until newsExpiration.expiryDate  %}
   Bla
{% endcache %}

Now the news entry has expired and no news is present so there is an error:

  Impossible to access an attribute ("expiryDate") on a null variable

I then wanted to write a conditional to see if newsExpiration is defined.

{% if newsExpiration is defined %}
   {% cache until newsExpiration.expiryDate  %}
{% else %}
   {% cache %}
{% endif %}

But that also throws an error because Twig is expecting a closing tag to the cache.

  Unexpected "else" tag (expecting closing tag for the "cache" tag
  defined near line xy).

I there a proper way to define the cache tag including both present and absent entries without query conditionals?


texts: Check if local image differs from image on Craft

texts:
I'm writing a plugin which synchronizes the content from an external database with the Craft database.

For the images I receive URL's to the external image then store them in the temp storage and upload them to Craft assets, which works fine.

I now want to check additionally if the image in the temp already exists in crafts assets and if the images are identical ( checking for file size ).

Ideally comparing the external image and the image in the assets even before saving the external one to the temp.

The file size from the external source is identical to the tmp saved file but after uploading the file to Craft it somehow gets a little bit bigger so checking for the file size doesn't work.

Am I doing something wrong ? Should I check for something else than filesize?

This might be related to this question


texts: How can I add a RichText-Field to my plugin's CP-section?

texts:
I'm trying to add a redactor richtext field to one of my plugin templates in the CP.

I found macros for every field in craft/app/templates/_includes/forms, but a richtext macro is missing. I assume that I have to use a normal textarea-field and add some code to the controller or init()-function, but couldn't find anything by inspecting Craft's CP code.


texts: How can I count current indexing inside a loop?

texts: Is it Possible to count current indexing in a loop which starts from indexing 1 as well as 0?


texts: Plugins - Element Criteria Model. Can I return only entries with a updated date in the last 7 days?

texts:
My plugin function is ignoring the dateUpdated criteria. Any clue as to why? I'm guessing it's syntax, but I cannot find any examples online as to how to format correctly. I can make this work in a template just fine. I'm new to plugins and PHP. Thanks!

$criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'guide';
    $criteria->order = 'postDate desc';
    $criteria->dateUpdated  > '("now"|date_modify("-7 days"))';
    $entries = $criteria->find();

    if ($entries) {
        //Do that thing with my code
    }


texts:
I'm trying to remove duplicate image objects from an array, but can't figure out why it won't find it:

{% for image in product.productGallery %}
    {% set productGalleryArray = productGalleryArray|merge([image]) %}
{% endfor %}

{% for variant in product.variants %}
    {% set variantImage = variant.productVariantImage.first() %}
    {% if variantImage|length and variantImage not in productGalleryArray %}
        {% set productGalleryArray = productGalleryArray|merge([variantImage]) %}
    {% endif %}
{% endfor %}

{% if productGalleryArray|length %}

        {% for image in productGalleryArray %}

        {% endfor %}

{% endif %}

Essentially what I'm trying to do is have a productGallery field which you can add images to, but also add an image to the product variant via productVariantImage.

This can cause the issue where by theres duplicate of the same image being output from the slideshow after it's merged the two fields together.

So I need to ideally:

Remove the duplicates before the array is merged, OR
Find and remove duplicates after the array is merged (Via a Twig filter?)


texts: Pagination - setting the default first page without url as /page/1

texts:
Pagination issue. What is the best method to resolve this?
So on a site I have a news section.
All links point to this page as /news/ so e.g. (http://www.website.co.uk/news)
I am then paginating this page like so:
{% set firstPending = craft.entries({
  section: 'news',
  status: 'pending',
  orderBy: 'postDate asc'
}).one %}
{% set cacheUntil = firstPending ? firstPending.postDate : now|date_modify('+1 year') %}

{% set news = craft.entries
  .section('news')
  .with('articleImages')
  .limit(4) %}

{# Get the articles and paginate them #}
{% paginate news as pageInfo, pageEntries %}

{# SEOmatic pagniate codfe into head #}
{% do seomatic.helper.paginate(pageInfo) %}

{% for entry in pageEntries %}
  <div class="max-w-4xl">
    {% include 'pages/news/_partials/_news-teaser.twig' %}
  </div>
{% endfor %}

the problem I am facing is that the standard news url is not getting any pageInfo, so it is breaking the pagination and not passing in the correct values.
If I access the URL at /news/page/1 I am seeing the pageInfo (e.g)
craft\web\twig\variables\Paginate#1
(
    [first] => 1
    [last] => 4
    [total] => '11'
    [currentPage] => 1
    [totalPages] => 3
    [craft\web\twig\variables\Paginate:_basePath] => null
)

Comes from {% dd(pageInfo) %}
My Question is, how can I make /news/ work as the first page in the pagination and ideally without changing the URL to /page/1 I would like the default (first page to remain as /news/).


texts: Craft Commerce multisite, different tax rates

texts:
In Craft 3, Commerce 2 is there a way to set a different tax category or rate on a cart/site when using commerce in a multi site environment? Site A (b2c website) has tax rate 1 (21% with tax included in price) and site B has tax rate 2 and 3 (21% with tax excluded in price and a 0% tax rate). Both sites use the same products/inventory but are targeted for different audiences (b2c and b2b).

I’m looking for a solution that works simular like posting  to the update-cart action when adding products to the cart.

Or, even better would be to be able to set defaults for the cart when setting {% set cart = craft.commerce.carts.cart %}.


texts: Twig variables wont work in an include js file?

texts:
Im trying to put my  code in a included theme.js file. It wont recognize my variables anymore.

Working in .rain file within the html code:

<script>
  jQuery(document).ready(function(){
    var uspicon1 = "{{ theme.usp_1_icon }}";
    var uspicon2 = "{{ theme.usp_2_icon }}";
    var uspicon3 = "{{ theme.usp_3_icon }}";
    var uspicon4 = "{{ theme.usp_4_icon }}";
    jQuery('.icon1').addClass(uspicon1);
    jQuery('.icon2').addClass(uspicon2);
    jQuery('.icon3').addClass(uspicon3);
    jQuery('.icon4').addClass(uspicon4);
  });
</script>

Not working with an include .js file:

  jQuery(document).ready(function(){
    var uspicon1 = "{{ theme.usp_1_icon }}";
    var uspicon2 = "{{ theme.usp_2_icon }}";
    var uspicon3 = "{{ theme.usp_3_icon }}";
    var uspicon4 = "{{ theme.usp_4_icon }}";
    jQuery('.icon1').addClass(uspicon1);
    jQuery('.icon2').addClass(uspicon2);
    jQuery('.icon3').addClass(uspicon3);
    jQuery('.icon4').addClass(uspicon4);
  });

Practicly the same without the script tags. I tested a console.log() and it works fine. I'm guessing it wont recognize my {{ variables }} in .js file.

Anybody know what the syntax is?


texts: Return JSON array without extra square brackets

texts:
I'm having difficulties to remove an additional set of square brackets or avoid including them within array.

My JavaScript code currently accesses array's object at 0 index and therefore I'd have to loop in one level deeper array. Which I'd like to avoid if possible.

This is my endpoint:

'pricelist/<entryId:\d+>.json' => function($entryId) {
    return [
        'elementType' => ElementType::Entry,
        'criteria' => [
            'section' => "products",
            'descendantOf' => $entryId,
        ],
        'transformer' => function(EntryModel $entry) {

            $products = [];
            // "orderItem" is entry field
            foreach ( $entry->orderItem as $product ) {
                $products[] = [
                    'title' => $product->titleVariation,
                ];
            }
            return $products;
        },
    ];
},

Returned JSON array is:

{"data":
    [
        [
            {
                "title": "a",
            },
            {
                "title": "b",
            },
            {
                "title": "c",
            }
        ]
    ]
}

Expected JSON array output:

{"data":
    [
        {
            "title": "a",
        },
        {
            "title": "b",
        },
        {
            "title": "c",
        }
    ]
}

I have almost the same scenario from this question but the answer wasn't my issue.


texts:
I have a handful of custom routes configured on this project like

'action/(?P<custom_id>[a-zA-Z][0-9]{6})/(?P<slug>.*)' => 'action/_member',

If I'm reading the docs correctly, then those need to change to become

'action/<custom_id:[a-zA-Z][0-9]{6}>/<entrySlug:{slug}.*>' => [
        'template' => 'action/_member'
    ],

but that gives me a template not found error when I hit localhost/action/L100582/&session=115

If I simplify the rule to become

action/steven' => [ 'template' => 'action/_member' ]

and hit, localhost/action/steven the template loads just fine.

I can't wrap my little head around what I'm missing.


texts:
So I am working on it first time. I created a Controller DB_DuhController having a method actionFoo()

I am then calling it as http://domain.craft.dev/admin/DB/duh/Foo but it's giving 404 all the time. What is wrong being done by me?


texts: How to extend a variable name to fetch another?

texts:
I’m trying to append a 'x2' to the end of a variable name to call another variable.

For example:

imgSize might be set to predefined variables like imgColumn4, imgColumn6 or imgColumn8.
In that case I would also have imgColumn4x2, imgColumn6x2 and imgColumn8x2.

So to simplify the variables in a loop, I’d like to do something like:

{% set imageUrl = image.getUrl(imgSize) %}
{% set imageUrlx2 = image.getUrl(imgSize ~ 'x2') %}

imgSize ~ 'x2' does not work.

How can I join 'imgSize' and 'x2'?


texts: Forcing destruction of httpSession variables on logout

texts:
I would like to store some data in the user's session specifically for when they're logged in. When logged out, I would like the session to destruct. Trawling through the code, it seems that session destruction is forced to false on logout.

yiilite framework:

public function logout($destroySession=true)

Craft UsersController:

 public function actionLogout()
 {
            craft()->userSession->logout(false);
....

I'm using the following in Craft config to force logouts and expiration after a certain amount of time, but the session doesn't get destroyed until the browser is closed.

'userSessionDuration'=>'PT20M',
'rememberedUserSessionDuration' => false,

Is there something I'm missing here, or do I have to override the event and clear the session variables myself?


texts:
So I am trying to create a new entry, but every time I click save, nothing is actually saved. (see gif)

THINGS I HAVE TRIED:

Overwriting the app folder with a freshly downloaded one (I am already on the latest stable build)
Increasing max_input_vars and post_max_size in my php config

THINGS I HAVE NOTICED

It works if I leave the rich text field blank, or with minimal content (like maybe 2 sentences)
Nothing ever makes it to the database, _entryversions remains unchanged
I don't see anything weird in my log, e.g. no [error] tags

Craft Version: 2.6.2990

Thanks in advance for your help!


texts:
I am running Craft CMS 3 and Commerce 2 on a virtual machine composed of Centos 7, Apache 2.4, PHP 7.2 and MySQL 5.7.22. It seems almost impossible working with the control panel with such huge response times:

http://craftcms/admin/dashboard takes 2.6s to load. (500ms on localhost MAMP)
http://craftcms/admin/settings takes 3s to load (350ms on localhost MAMP).

I've tried the following stuff:

assigned php memory_limit to 512M in php.ini
connecting to MySQL using 127.0.0.1 instead of localhost (.env)
set HostnameLookup Off in apache httpd.conf
set ServerName 10.10.0.20 in apache httpd.conf
accessing the page via 10.10.0.20 instead of virtual host craftcms
removed usage of .htaccess file following this guide
unloaded unnecessary apache modules
disabling cgi apache module

Looking at the network statistic the TTFB takes 4.28s and whole page loads in 5.01s. I am assuming it's the configuration issue since when running MAMP on windows everything responds a lot quicker. Any ideas what I should be looking at or is this performance as intended?

What strikes me the most is that phpmyadmin responds very quickly. I tried running a standalone (non-Craft) page with and without PHP. Page with PHP loaded cca 20ms longer. I would assume PHP doesn't cause mentioned problems.

craftcms.conf:

<VirtualHost *:80>
    DocumentRoot "/opt/webroot/craftcms/web/"
    ServerName craftcms
    ErrorLog "/var/log/httpd/craftcms-error_log"
    CustomLog "/var/log/httpd/craftcms-access_log" combined

    <Directory "/opt/webroot/craftcms/web/">
        Options FollowSymLinks
        AllowOverride None

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

Update:

After disabling unnecessary apache modules responses are a lot faster. I also tried using worker and even MPM, changes in timings were neglectable.

Update2:

Craft3 debug toolbar shows the following critical timings when loading settings page:

11:43:00.140  1098.4 ms   craft\web\twig\Template::display    settings
11:43:00.154  1083.8 ms   craft\web\twig\Template::display    →_layouts/cp
11:43:00.374  863.6 ms    craft\web\twig\Template::display    →→_layouts/basecp
11:43:00.375  862.4 ms    craft\web\twig\Template::display    →→→_layouts/base

This is output of same data on localhost:

11:52:46.713  124.0 ms    craft\web\twig\Template::display    settings
11:52:46.716  121.4 ms    craft\web\twig\Template::display    →_layouts/cp
11:52:46.743  94.4 ms craft\web\twig\Template::display    →→_layouts/basecp
11:52:46.743  93.9 ms craft\web\twig\Template::display    →→→_layouts/base

The difference in timings is quite big.


texts: How can I get image locations in a list of entries using the Element API plugin?

texts:
'api/looks/list' => [
        'criteria' => ['section' => 'looks'],
        'transformer' => function(EntryModel $entry) {

                //print_r($entry->getAncestors());
                // $model = $entry->content->attributeConfigs["featuredImage"]["model"];
                // echo 'class type: ' . get_class($model);
                // print_r($model);

            return [
                'title' => $entry->title,
                'id' => $entry->id,
                'url' => $entry->url,
                'jsonUrl' => UrlHelper::getUrl("looks/{$entry->id}.json"),
                'kachelgroesse' => $entry->kachelgroesse,
                'category' => $entry->category,
                'image' => $entry->image
            ];
        },
    ],

This is my elementapi.php file and it returns:

{
  "data": [
    {
      "title": "SHINY AND RED LIPS",
      "id": "281",
      "url": "http://craft.dev:8888/looks/shiny-and-red-lips",
      "jsonUrl": "http://craft.dev:8888/looks/281.json",
      "kachelgroesse": {
        "0": {
          "label": "mittel",
          "value": "mittel",
          "selected": true
        }
      },
      "category": {
        "0": {
          "label": "Make-Up",
          "value": "Make-Up",
          "selected": true
        }
      },
      "image": {}
    }
  ],
}

There is no image returning.  I am requesting the list of all entries and their image/asset location from the API.


texts: table field - make one culumn translatable, other common for all languages

texts:
Lets say i have table field with product technical specification - two columns, one for feature name, one for feature value.

Feature name (for example - "weight") needs to be translated across various languages. Feature value needs to always stay the same (for xample - "1kg").

How can this be achieved?


texts: Entry versioning history only shows last 10 versions

texts:
My client wants to look through very old versions of a certain page entry, but the Recent Versions drop-down is only showing a max of 10 entries. I know that older versions of the page exist because if I change the last number in the URL (of a more recent version) and I can access much older entries. Unfortunately, the are organized numerically by date (and not by page) so it makes them almost impossible to sift through.

Any help would be appreciated.


texts: Trouble with Restrict to Single Folder and Upload Location

texts:
I have a Matrix field with two blocks. Each block has an assets field that I'm trying to set to restrict to uploads to a single folder and setting the upload location to {slug}. Basically what I'm trying to do is set up a main folder for my portfolio. I want to be able to upload images for each entry and have them placed in a folder with the same name as the entry so whenI look in Assets I see something like:

Portfolio
-- project 1 entry name
-- project 2 entry name
...
-- project 17 entry name
-- project 18 entry name

When I upload the file in my entry form no subfolders are created. I have tried a few things to remedy the problem to no avail. I've set permissions to 777 and have tried placing a / before {slug} because the fileSystemPath variable doesn't have a trailing slash in my general.php config file. Any other issues that might cause this?


texts: How can I create a template macro within my plugin for use within front end templates?

texts: I have a plugin that I am writing and I want to make available a macro that can be used within the front end sites templates. What is the best way to do that?


texts: Search with string, entry type and category

texts:
So I have been asked to build a resource center just like hubspot's. (insert rolleyes here)

https://www.hubspot.com/resources

You can click into a type, and then click at topic and it creates a url like so:

https://www.hubspot.com/resources/ebook/advertising

You can also click a topic and then click type and it will do the same.

I have this part pretty much working. In my category template I have done this:

    Filter by type:

    case studies

    ebooks

    webinars

    whitepapers

then I have a routes for each type setup like this:

if the URI looks like this:

/resources/case-studies/*

Loads this template:

resources/_filtered.html

and in that template filtered I do the filtering like this:

        {% set resourceType = craft.request.segment(2) %}

        {% set resourceCatSlug = craft.request.segment(3) %}

        {% set resourceCat = craft.categories.slug(resourceCatSlug).first() %}

        {{resourceType}}

        {{resourceCat}}

        {% set filteredEntries = craft.entries({
            section:    ['resources'],
            orderBy:    {postDate: SORT_DESC},
            type:       resourceType,
            relatedTo:  resourceCat,
        }).all() %}

This all works and I planned to do the same method on the resources types to get to the filtered template.

But where I'm stuck is it was also requested that you could filter your search even further with a string search.

So from this:

<form class="control txt-center" action="{{ url('resources/search/results-filtered') }}">

<input class="input margin-auto-left-right display-block is-narrow-field " type="search" name="q" placeholder="Search">

<button class="margin-top-1 button is-info" role="button" type="submit"> Search the library </button>

How can I pass entry type and category to my filtered results?

{% set searchTerm = craft.app.request.getParam('q') %}
{% set searchResults = craft.entries.search(searchTerm).section('resources').orderBy('score') %}

PS, If anyone has a more elegant way to handle this I'm all ears!


texts: Let user add a message when selecting shipping method

texts:
One of our shipping methods let's the customer have their purchase delivered at home. When the user selects that method, we'd like to include a simple textarea where the user can write when he wants his order delivered.

Is there an easy way to go about this? Basically just attach a "user note" to the cart as a whole, not to any individual lineItem

Thanks!


texts: Calling onSaveEntry event only for one section

texts: Using the entries.onSaveEntry event, how would I ensure it's only applied to entries in a particular section? Or is there a way to make a distinction between an entry saved from the control panel and an entry created on a front-end form?


texts: Change matrixblock field value before save element

texts:
So i have a Matrix with one type of matrixblocks.
These all have a field for a custom id which should be set by the system, if empty, before the entry is saved.
I can access the individual matrixblocks and change the field value in all of them. But i am not sure how to add them back to the matrix so the changes will apply.
example code that is not working:


texts: How can I include a Users picker in a custom field type?

texts:
I would like to include a Users picker in a custom field type. Not sure if this is possible and practical.

Do you know how I can accomplish this, or can you point me in the right direction for self-education?

I see there is no users macro in /app/templates/_includes/forms.html, /app/fieldtypes/UsersFieldType.php has almost nothing in it, and I don't know enough about the system yet to know where else to look for ideas.


texts: Fatel error message when saving post/pages

texts:
Why do I sometimes receive the following message when I save a change made to a page:

  Fatal error: Call to a member function getAttributes() on a non-object
  in
  /nfs/c04/h06/mnt/181592/domains/imperfectinteriors.co.uk/craft/app/controllers/EntriesController.php
  on line 444

Although it is an error message, the save is successful and the change is reflected in the site.

Thanks.


texts: How to use better loop for my product images

texts:
I have a main product image and 4 thumbnails. Main product image is a lightswitch which is named productMainImage.

Here below i first iterate for the main image (which lightswitch is on) and than i make a second for loop for 4 thumbnails.

My problem is i don't like this code and it seems inefficient. I have to go out and go in for the loop because of my html stucture.

Can anyone help me to write this better?

    {% for image in product.productImages %}
      {% if image.productMainImage %}

        {% endif %}
    {% endfor %}

        {% for image in product.productImages %}

        {% endfor %}


texts: 404 when clicking on the Disqus embed urls

texts:
I've just noticed on a site that the Disqus comment embed is suggesting other articles but they're adding a token to the end of the URL, for example:

http://australia.thegospelcoalition.org/article/blessed-to-be-rich-a-biblical-theology-of-blessing?token=_g6RQbb8oD9~uxEUu8u6~c9875m17~jo

But this returns a 404 in Craft. Works fine without that query string.

Any ideas to resolve?


texts:
Has anyone ever tried and/or succeeded at integrating a SCORM player with Craft?

I'd like to "roll my own" LMS in Craft because Moodle is WAY overkill, but I need to be able to deliver SCORM content, as well as access and utilize the data provided by the SCORM files.


texts: Twig Templating If statement (Unexpected tag name error)

texts:
Sorry if this is a really obvious question, I'm new to Twig and Craft. I'm getting the following error:
Unexpected tag name "offset" (expecting closing tag for the "if" tag defined near line 54)

Can anyone tell me what is wrong with my code?

{% set offset = true %}
{% if offset %}

    {% set caseHero = entry.heroImage.first() %}

{{entry.title}}

{{entry.description}}

    {% offset = false %}
{% else %}

    {% set caseHero = entry.heroImage.first() %}

{{entry.title}}

{{entry.description}}

    {% offset = true %}
{% endif %}


texts: How to loop through multiple entries fields

texts:
I'm creating a dynamic side navigation where pages can choose which sidebar it wants to use. This is selected by an entries field called 'sidebar' - called in line 2.
To create this I've made a structure called 'Sidebars' with an entry for each sidebar type.
Each Sidebars entry has an entries field in it which can select any number of pages.
I've got it fully working, but it's giving me deprecation errors.
Here's the working (but deprecated code on line 4):
(lines 5-12 figure out whether the path includes 'whats-on' or 'who-we-are' and adds them to the path to the entry if needed).

  {% set sidebarChoice = entry.sidebar.one() %}
  {% for rel in sidebarChoice %}
    {% for sidebarEntry in rel %}
      {% set myEntryQueryUrl = sidebarEntry.url %}
      {% if 'whats-on' in myEntryQueryUrl %}
        {% set myEntryQueryPath = '/whats-on/' %}
      {% elseif 'who-we-are' in myEntryQueryUrl %}
        {% set myEntryQueryPath = '/who-we-are/' %}
      {% else %}
        {% set myEntryQueryPath = '/' %}
      {% endif %}

{{ sidebarEntry.title }}

{{ sidebarEntry.title }} text

    {% endfor %}
  {% endfor %}


texts:
I have the following 1:n relation between two sections:

Source Element: Interview
Target Element: Persons

In the CP (only there) I need to be able to identify Interviews by the name of the interviewed persons.

So in the title format field for the entry type I tried something like

{date}-{relation_interview_persons[0][firstname][lastname]}

But that's no good.

Is that even a valid approach?
Of course, we can simply use a custom title and that's it.


texts:
I'm trying to use this slightly differently:
How do I omit similar content in a for loop based on the first letter in title?

I have a for loop with several entries. One field is a drop-down with a bunch of vendors listed, and the user can select only one. I want a list of vendors that have been selected in the entries so that somebody can click on the vendor and see only the entries associated with that vendors. Clear as mud?

If no vendor is in any entries, then it should not be on the list.

{% set vendorArray = [] %}

{% for entry in craft.entries.section('orderBook').order('vendor').all() %}
  {% if entry.vendor not in vendorArray %}
    {% set vendorArray = vendorArray|merge([entry.vendor]) %}
  {% endif %}
{% endfor %}

{% for link in vendorArray %}
  {{ link }}
{% endfor %}

The above link shows this working with only using the first letter of a field. I  want to use the entire field. I removed the filter |first and then I start to get duplicate vendors. I think the solution has something to do with the operator "not in", but I'm a noob so not too sure.


texts: How can I test if a request returns a 404?

texts: In my 404 template I am extending a layout template. Inside that layout template I want to hide a section use an {% if craft.request... == 404 %} test. Any ideas on how I can accomplish this?


texts: Deleting stale template stuck fatal memory error

texts:
So all my background tasks Craft 3.2.6 seem to process ok except deleting stale template caches. Although craft is supposed to fail after 5 minutes, it fails instantly and the error log shows

Allowed memory size of 1610612736 bytes exhausted (tried to allocate 380928 bytes)

Server settings for memory are 512M and 300 second timeout. The error is instant - in that the error log is immediately populated on saving an entry - which makes me think that this is not the real problem. The server is running Nginx as a reverse proxy for apache and uses microcaching and I wonder if this might interfere with that one task?
Its a multisite with 8 languages and I guess quite heavy on the fields and image processing.
How can I debug this further - short of giving the whole dedicated box memory to this one site?


texts:
Sometimes when your javascripts or stylesheets are formatted a certain way, twig seems to try and render those snippets (whom always include curly brackets in some way).

For example, if you end you're CSS stylesheet with something like this;

@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

(I can't remember the exact case off the top of my head, but I believe this is it)

The stylesheet won't render, as twig throws an exception giving you a 500 error. It seems to be that the curly brackets (two next to each other in the flow) gets interpreted as twig.

The same goes for JavaScript, where a concrete example is instafeed.js if you import and compile with Parcel or Webpack or the likes, there's a line of code in that library that makes the .js file throw a 500 error because twig interprets the file. Specifically this line;

pattern = /(?:\{{2})([\w\[\]\.]+)(?:\}{2})/;

Again the curly brackets breaks the loading of the .js file.

I actually haven't gotten around to simply loading the javascript and css though basic tags in the html, so it might be that the issue is only present when loading through {% do view.registerCssFile(url) %} or {% do view.registerJsFile(url) %}.

Any simple workaround for this (maybe just loading with html like <script src="{{ path-to-file }}">)?


texts: Unable to delete Entry: Numeric value out of range

texts:
I have a Structure section that I converted to a Channel. I then tried to delete an Entry Type from the Control Panel and get the following error:

{"error":"SQLSTATE[22003]: Numeric value out of range: 1690 BIGINT UNSIGNED value is out of range in '(`databasename`.`craft_structureelements`.`level` - 2)'\nThe SQL being executed was: UPDATE `craft_structureelements` SET `level`=`level`-2, `dateUpdated`='2019-05-26 04:16:54' WHERE ((`lft` >= 128) AND (`rgt` <= 129)) AND (`root`=21)"}

Upon closer inspection, I'm able to delete many of the Entries of that Entry Type if I delete them directly but there is one that I cannot delete directly which seems to be the source of the error above.

I have found a general discussion of a similar mysql error but I haven't found any Craft specific discussion of this. As I'm trying to make the delete action from the Craft UI, the general solutions are not directly applicable.

Any ideas what might be going on here and what my options are to fix this and get the Entry Type in question deleted without any unexpected side effects?


texts: Updating plugin/module config via template/controller

texts:
I have a plugin/module that synchronises local records with a Google Sheet managed by the client.
The URL for this doc is stored in a module config.
I want the client to be able to update this via the control panel so have created a template for editing and a controller to update the config. This is all fine locally but in the client environment where allowAdminChanges is set to false this won't save and I get the following error:
 Changes to the project config are not possible while in read-only mode.

I have tried both Craft::$app->projectConfig->set('my-module', $settings); and Craft::$app->getSystemSettings()->saveSettings('mud-module', $settings) with same ersponse.
Is there a way to update config when allowAdminChanges is set to 0/false?


texts:
I'm looking for a way to list all the enabled sites for a given entry.
 I couldn't find some sort of getEnabledSites method that's similar to the available getSupportedSites.  The latter only returns the siteId and enabledByDefault properties.

Note that I'm doing this within the Element API plugin.


texts: Need to create dynamic CSS names for buttons

texts:
This may not be the most efficient approach for this specific case but I'm trying to learn how this might be done for other similar problems I might run across in the future so bear with me here.

I have a Global that creates links to social media sites on my profile page. My fields include icon (asset), name (text), url (text), and color (color). I have included the following at the top of my template:

{% set buttonCSS %}
    {% for block in contactLinks.contactLinks.type("contactLink") %}
    .{{ block.contactLinkName | lower }}:hover {
        background-color: {{ block.buttonColor }}
    }
    {% endfor %}
{% endset %}

{% includeCss buttonCSS %}

This generates dynamic styles for each button at the top of my profile page so I can add links. My template then generates the links:

{% for block in contactLinks.contactLinks.type("contactLink") %}

{{ block.contactLinkName }}

{% endfor %}

Now, for the most part this works since social media sites tend to be one word but when I tried to use "Let's Talk" for my email link I run into problems with the CSS. What's the best way to strip the apostrophe and spaces from my class names?


texts: Get entries that are enabled and disabled for the site

texts:
A Craft (3.4 Pro) website has setup two sites, one for each language. There are entries in a section that are enabled and others that are disabled for each language.
I want to get a list of all the entries, regardless of whether they are enabled or not.
I know there is a enabledForSite parameter but this can be set to either true or false but not both.
For example the query below returns only enabled entries.
{% set items = craft.entries({
  section: 'works',
  enabledForSite: true,
  status: [
    'live', 'pending', 'disabled', 'expired'
  ]
}).all() %}

How can I get a list that contains both enabled and disabled entries?


texts: Error trapping on discount codes based on Cart contents

texts:
Is there any automatic Error trapping built into Craft for discount codes for the following rules?

Orders over a set Total
Orders over a set Quantity

The codes work/apply, but if the rules don’t match I am not getting any errors/messages back.
Any ideas? Do we have to write checks for every scenario?

There are likely more scenarios than the two I have listed above. It seems a little poor UX to appear to do nothing, no error, no discount applied if the contents of the cart don't qualify.


texts: How to output taxCategory in Craft Commerce

texts:
I'm trying to test for a taxCategory within Craft Commerce and finding it awkward to do so. I can't see much in the docs, but have managed to put this together:

{% if product.taxCategory | length %}
    {% for taxCategory in product.taxCategory %}
        {# loops through the taxCategory with the first string being the id, #}
        {# the second the name and the third string seems to be the slug #}
        {% if loop.index == 3 and taxCategory == "withVat" %}
            +VAT
        {% endif %}
    {% endfor %}
{% endif %}

But it doesn't seem very elegant. Any suggestions? The docs example probably needs updating, I think, because:

{% for taxCategory in craft.commerce.taxCategories %}
    {{ taxCategory.id }} - {{ taxCategory.name }}
{% endfor %}
{% endif %}

...outputs: "Impossible to access an attribute ("id") on a string variable"


texts: How to get a result from search even if the search query contains a part of title?

texts:
Suppose there are three Entries:

Entry One
Section One
Channel One

I need to get Section One in result when I search Sect. Is this possible ? I am using

{% set entries = craft.entries.search(query) %}

to get the results. But keyword sect doesn't return any result.