texts: Can you lookup the value in a key-value array with the value in an entry field?

texts:
This might be impossible, but can you lookup a value in a key-value array with the value in a craft entry field? And perform math with it in twig? I'm trying to simplify my template code.

I have a key value array like so

{%
set aspectRatioSetting = {
    'four_three' : '0.75',
    'three_two' : '0.666666666667',
    'sixteen_nine' : '0.5625',
    'one_one' : '1'
} %}

And I'd like to be able to use those values in a math operation, the specific value looked up by a value in a custom entry field.

{% set transformParams = { width: 1250, height: 1250 * aspectRatioSetting.four_three } %}

where the value of the "four_three" key in the array is used in the math operation. Only the specific key would be set by the value in an entry field.

{% set transformParams = { width: 1250, height: 1250 * aspectRatioSetting.(entry.aspectRatio) } %}

There's not a good way for me to type it up because this clearly doesn't work. I'm just wondering if it's somehow possible.

Or maybe I'm just overcomplicating things in an attempt to simplify things : /


texts: Checking if current entry exists in an entry custom field in a different entry

texts:
I thought this would be simple but I am having no luck with it. I have a channel called "Posts" and for each Post there an "entry" custom field which lists all "Projects" (a structure). The user can select up to 3 of these within a Post.

The idea is to relate a current news Post with an existing project. In my Project entry template I basically want to check to see if the current project has been selected in the "relatedProjects" entry field. If it has, I need it to show a "Related Posts" title and then below that list each Post.

The thing I can't fathom out is how to have a section title that doesn't appear in the loop for each Post.


texts:
I tried searching for an answer for my situation but I could not find one. I tried following the steps here https://docs.craftcms.com/v3/upgrade.html#preparing-for-the-upgrade but whenever I get to the browser step to complete upgrade, I get this error:

  !/usr/bin/env php
  Exception 'yii\base\UnknownPropertyException' with message 'Getting unknown property: craft\console\User::enableSession'

  in /Users/avalosju/craft/vendor/yiisoft/yii2/base/Component.php:154

  Stack trace:

  0 /Users/avalosju/craft/vendor/craftcms/cms/src/helpers/App.php(372): yii\base\Component->__get('enableSession')

  1 /Users/avalosju/craft/vendor/craftcms/cms/src/config/app.php(214): craft\helpers\App::logConfig()

  2 [internal function]: {closure}()

  3 /Users/avalosju/craft/vendor/yiisoft/yii2/di/Container.php(503): call_user_func_array(Object(Closure), Array)

  4 /Users/avalosju/craft/vendor/yiisoft/yii2/BaseYii.php(351): yii\di\Container->invoke(Object(Closure), Array)

  5 /Users/avalosju/craft/vendor/yiisoft/yii2/di/ServiceLocator.php(137): yii\BaseYii::createObject(Object(Closure))

  6 /Users/avalosju/craft/vendor/yiisoft/yii2/base/Module.php(742): yii\di\ServiceLocator->get('log', true)

  7 /Users/avalosju/craft/vendor/craftcms/cms/src/console/Application.php(146): yii\base\Module->get('log', true)

  8 /Users/avalosju/craft/vendor/yiisoft/yii2/base/Application.php(508): craft\console\Application->get('log')

  9 /Users/avalosju/craft/vendor/craftcms/cms/src/base/ApplicationTrait.php(1133): yii\base\Application->getLog()

  10 /Users/avalosju/craft/vendor/craftcms/cms/src/console/Application.php(62): craft\console\Application->_preInit()

  11 /Users/avalosju/craft/vendor/yiisoft/yii2/base/BaseObject.php(109): craft\console\Application->init()

  12 /Users/avalosju/craft/vendor/yiisoft/yii2/base/Application.php(206): yii\base\BaseObject->__construct(Array)

  13 /Users/avalosju/craft/vendor/yiisoft/yii2/console/Application.php(89): yii\base\Application->__construct(Array)

  14 /Users/avalosju/craft/vendor/craftcms/cms/src/console/Application.php(53): yii\console\Application->__construct(Array)

  15 [internal function]: craft\console\Application->__construct(Array)

  16 /Users/avalosju/craft/vendor/yiisoft/yii2/di/Container.php(383): ReflectionClass->newInstanceArgs(Array)

  17 /Users/avalosju/craft/vendor/yiisoft/yii2/di/Container.php(156): yii\di\Container->build('craft\console\A...', Array, Array)

  18 /Users/avalosju/craft/vendor/yiisoft/yii2/BaseYii.php(349): yii\di\Container->get('craft\console\A...', Array, Array)

  19 /Users/avalosju/craft/vendor/craftcms/cms/bootstrap/bootstrap.php(252): yii\BaseYii::createObject(Array)

  20 /Users/avalosju/craft/vendor/craftcms/cms/bootstrap/console.php(31): require('/Users/avalosju...')

  21 /Users/avalosju/craft/craft(21): require('/Users/avalosju...')

  22 /Users/avalosju/craft/web/index.php(19): require_once('/Users/avalosju...')

  23 {main}


texts: Multiple backends on CraftCMS 3 - Problem with cpresources

texts:
We've got a AWS setup with an ELB in front, 2 varnish cache servers and 2 Craft CMS backends, with Redis for php sessions and Craft cache shared amongst the backend servers.

We do not have sticky sessions, so each request can end up on a different server.

Problem is with cpresources and the generated files. First request generates files on server 1, but as each request can end up on a different server, the other servers will not have the same files.

What is the best approach here? What alternatives do we have?

We would like to avoid sharing cpresources amongst the servers if possible (via mount), as it slightly complicates setup and its "one more thing that may break".

-- Edit

We have been experimenting with AWS EFS (Elastic File Storage) to share disks between servers, but unfortunately its too slow.

We noticed that in Craft CMS 2, static files were served through index.php, which allows php to create the files, should they not exist, which would solve this particular issue. However, in Craft CMS 3, this changed and they are served directly. It would be great if someone official in Craft CMS could verify this change and comment why it was designed the way it is in Craft CMS 3 and also comment on how that change is beneficial in a multi-backend-setup.

We are now looking into an EC2 instance to serve the purpose of an NFS share, but doing this we are introducing a single point of failure in an architecture that was suppose to eliminate that exact thing.


texts: Change position of entry types in a structure

texts:
I was wondering if there's a way to change the position of elements in an entry type structure. I want to change the positions of the elements when a user logs in, so I'll write it in a plugin.

Any Ideas?


texts: Is it possible to order entries by Entry type title/slug

texts:
I would like to order my entries by the entry type they have, so for instance:

{% set entries = craft.entries.section('more-info').order('type') %}

However, this orders by entry type ID, and not by title, alphabetically. Can this be done? I've tried order('type.title'), but no luck (= DB error) ...


texts: Is it possible to route a subdomain to specific template group?

texts:
We are looking for a way to route a subdomain to a specific template to use as a landing page.

Is there a way to do this without routing through index.html and redirecting to the specified template folder and file?

I can confirm that using the redirect does lose some of the user information, tracking codes etc. However it does retain the referral url from the 3rd party site.


texts:
I have the following XML:

<nodes>
    <node>
        <title>Test Org - Pleae Ignore</title>
        <logo>
            <enclosure url="https://www.mydomain.org/sites/default/files/louis%20xiv.jpg" length="71280" type="image/jpeg" />
        </logo>
    </node>
    <node>
        <title>Test Org - Pleae Ignore</title>
        <logo>
            <enclosure url="https://www.mydomain.org/sites/default/files/louis%20xiv.jpg" length="71280" type="image/jpeg" />
        </logo>
    </node>
    <node>
        <title>Test Org - Pleae Ignore</title>
        <logo>
            <enclosure url="https://www.mydomain.org/sites/default/files/louis%20xiv.jpg" length="71280" type="image/jpeg" />
        </logo>
    </node>
</nodes>

And the following template markup:

{% set params = {
    url: 'https://www.domain.org/xml-details?nid=12345',
    type: 'xml',
    element: 'node',
    cache: 60,
} %}

{% set feed = craft.feedme.feed(params) %}
{% for node in feed %}
    {{ node.title }}
    {{ node.logo.enclosure.attributes.url }}
{% endear %}

{{ node.title }} displays fine, but {{ node.logo.enclosure.attributes.url }} displays nothing.

Based on other threads I've read, I've also tried {{ node.logo.enclosure['@url'] }}

Neither returns the value of the url attribute.

Any help getting this to work is appreciated.

EDIT: Using just {{ node.logo }} in the template outputs <enclosure url="https://www.mydomain.org/sites/default/files/louis%20xiv.jpg" length="71280" type="image/jpeg" />.

EDIT: Here's my {{ dump(node) }} output.

array(30) {
  ["recordId"]=>
  string(5) "19795"
  ["title"]=>
  string(22) "Robertson Blood Center"
  ["summary"]=>
  string(101) "
Volunteer- Donate blood. Your donation of life is used by wounded military at home and abroad.
"
  ["logo"]=>
  string(156) "<enclosure url="https://www.mydomain.org/sites/default/files/1959440_10152076927213038_3915913252856478361_n%5B1%5D_2.jpg" length="35608" type="image/jpeg" />"
}


texts: Associating related entries to a new entry when using the API

texts:
This may just be a 5PM Friday issue, but I'm scratching my head over here. I'm trying to associate a string of related entry id's represented by a variable with a new entry via the API. When I pass the variable, only the first one gets inserted into the DB. If I use the string they all get inserted. Here's the insert code:

 $article_countries = "1021,1047,1076,1123";

 $entry->getContent()->setAttributes(array(
   'article_countries' => array(
     $articleCountries
    )
 ));

Why is the string working where the variable isn't?


texts:
I have a remote repository with a Craft install and am trying to pull it to a new environment. I run the composer install and Craft & other packages install seemingly correctly, added the .env file and set up the Apache server to point to the /web folder.
When I load up the url I get a visual of the index.php file:

  // Set path constants define('CRAFT_BASE_PATH', dirname(DIR));
  define('CRAFT_VENDOR_PATH', CRAFT_BASE_PATH.'/vendor');

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

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

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

No urls seem to be working e.g. /admin or /index.php?p=admin/install and I can even put anything as the url and nothing errors, just shows this file still.


texts:
Trying to create a page link to entries and can't figure out how to do it.  Here's what I have.  It's just outputting the title, but not the url.  Specifically, I'm talking about {{ block.pageLink.first }} Any help is much appreciated.

{% for block in entry.threeHomepageImages.type('images') %}

                {% if block.image|length %}

                {% endif %}

{{ block.imageTitle }}

{% endfor %}


texts: Access POST data to conditionally display form

texts:
I'm working with the contact form plugin and would like to test for post data to see if the form was just submitted.

It seems this code always throws a template error.

Variable "test" does not exist

Is there a better way to do this?

{% set success = craft.request.getPost(test) %}
{% if success %}
    form was just submitted
{% endif %}


texts:
I am new to Craft and am trying to figure out what the best way to set the $craftPath PHP variable to something like the other configurations for multi-environments.

Locally I have it set up the preferred way, but on my remote server, it's nested an extra level deep in folders (sub domains).

Is there a way to have the variable be set using the same functionality that Craft uses to determine environments? Or do I have to just manually change the value where the index.php lives.

Thanks for the advice.


texts:
I have looked around but cant find an answer to this.

I have a structure for my gallery page, in-which there are three separate entries called A, B and C.

There are different images within these entries. But how would I go about showing all the images within these entries in a random order?

Say I went to the gallery page and they all showed up randomly, then theres a sub navigation to the separate entries on there own?

It's probably a simple solution but templating it has me really confused.
Thank you


texts: "Fatal Error 'OAuth\Common\Storage\Session' not found" when trying to connect to connect to Google or Vimeo

texts:
I purchased the Dukt Videos plugin and when trying to connect with one of the services (Google or Vimeo) I'm met with the following fatal error:

( ! ) Fatal error: Class 'OAuth\Common\Storage\Session' not found in /home/forge/website.com/craft/plugins/oauth/providers/BaseOAuthProviderSource.php on line 51
Call Stack
#   Time    Memory  Function    Location
1   0.0001  242088  {main}( )   ../index.php:0
2   0.0002  243000  require_once( '/home/forge/website.com/craft/app/index.php' )   ../index.php:36
3   0.0392  3729440 CApplication->run( )    ../index.php:62
4   0.0392  3731160 Craft\WebApp->processRequest( ) ../CApplication.php:180
5   0.0617  4905776 Craft\WebApp->_processActionRequest( )  ../WebApp.php:263
6   0.0617  4906040 CWebApplication->runController( )   ../WebApp.php:756
7   0.0623  5054240 CController->run( ) ../CWebApplication.php:282
8   0.0625  5080680 CController->runActionWithFilters( )    ../CController.php:265
9   0.0625  5080792 CController->runAction( )   ../CController.php:286
10  0.0626  5081528 CInlineAction->runWithParams( ) ../CController.php:308
11  0.0626  5083200 Craft\OauthController->actionConnect( ) ../CInlineAction.php:49
12  0.0765  5789632 OAuthProviderSources\BaseOAuthProviderSource->initializeService( )  ../OauthController.php:120
13  0.0765  5789672 OAuthProviderSources\BaseOAuthProviderSource->getStorage( ) ../BaseOAuthProviderSource.php:124

This aspect of the plugin works on my dev env but when testing this on another separate install on my webserver this error keeps coming up.

Anyone have an idea how this can be fixed? Assuming it's not a plugin bug.

I have contacted the plugin developer about the issue but I'm concerned that I won't get a reply as I've asked him about another issue I encountered with the plugin about 2 weeks ago (with a follow up last week) and I did not get any reply. I've also seen that another member of this community had an issue with a plugin from the same developer and received no reply from the developer either. If this was a free plug in I wouldn't be expecting support but when you consider that the plugin costs €49, it's quite disappointing that there isn't a reply.

Thanks in advance!


texts: If URL Contains x Then Do Y in Twig / Craft Template?

texts:
I've got a website that has a resource center, news center and blog where each of those sections has a high quantity of assets that can be filtered by topic / type / date, etc. Additionally, due to the quantity of assets, we're using pagination to spread the assets across multiple pages.

All of the filtering and pagination creates a variety of worthless but currently crawlable URLs that we'd like to hide from the search engines.

I'm attempting to deploy the meta name="robots" content="noindex, follow" tag to all of the paginated / filtered URLs while keeping the overview pages indexed. It seems that the most logical way to do that is based on a consistent URL string that appears in both pagination and filtering instances.

How can I add a rule within my template that will insert the meta tag based on whether or not a string exists in the current URL appearing in a user's browser?

Any help would be much appreciated. Thanks!


texts: Filter entries in the CP based on custom permission

texts:
We started a new project, a website that lists products based on regions (for example US and Europe). We have all products in 1 channel (to make it dynamic to add more regions later on) and have a region field added to those entries (a checkbox field). We now want to hide products for specific users in the CP.

Through this thread I was able to add custom permissions via my plugin and it pointed me towards this event onBeforeBuildElementsQuery that I could use to add my custom filtering.
I think I may need to add a custom param with the value of what the regio field needs to be to the ElementCriteriaModel.

But I have no idea how to build the next steps. I don't really understand what that ElementCriteriaModel returns. It's just a model with all basic attributes, no custom fields or anything. No clear section it targets...

The next steps should be:

Is the event triggered by the CP?
If so, check the logged in user's permissions and decide what regio should be filtered
Add an extra param to the criteria that filters to correct region
Send the changed ElementCriterioModel (or Query) to wherever it needs to go

So, how do I insert a custom parameter into that ElementCriteriaModel and will it alter the entries that are visible in the CP? Am I on the right track here?


texts: BaseController::returnJson & devMode interference

texts:
While developing an API for a client site I recognized that there was a  tag being returned after our JSON response (generated using BaseController's returnJson method).

I copy & pasted some of the output into The Google and found a reference to the YII_DEBUG constant. I checked the value (true) and assumed it was related to devMode. I turned off devMode for this environment and the extra code went away (and YII_DEBUG===false).

I don't suspect that this extra output is expected while using the returnJson() method but I need to get around this. Can I turn off devMode outside of the config file? I really only want to make an exception when calling this method.


texts:
I’m looking to hook into existing modal functionality, if any exists.

Is there any way of doing this?

If there is, what’s the advised approach and considerations required to ensure responsiveness?


texts: What is "Temp Uploads Location" in Craft 3.2.10

texts:
In Craft (Solo) 3.2.10, In Settings > Assets > Asset Settings, there's a field called "Temp Uploads Location". I do see images in mine that I intended to go into the system, but not into there.

What is that feature for?


texts:
Is it possible to pass a value from Craft global setting into a CSS/SCSS file? So for example I want to be able to allow the end user to customise colours and fonts without having to include it inline.

Has anyone achieved this or similar?

Many thanks


texts:
So, I'm kinda new to Craft so there might be a easy trick to do this but I can't seem to get it working (even with some heavy googling).

On the homepage I've got three entries (from the Projects page) loaded and I'd like to load +3 more entries everytime a 'load more' button is clicked. I've already figured out the best way to do this is using the {% paginate %} function limited to 3 entries but thats where I'm kinda stuck right now..

Is there a way to change the limit on click or something better?


texts: Determine a layout based on column number

texts:
Okay, I want to create a Matrix based layout like this:

| x | x | x |
| x |   y   |
|   y   | x |

X is a 1/3 column and Y is a 2/3 column.

I want to activate the size Y with a lightswitch.

The problem is: If I have | x | x |   y   | the layout will blow up because there are too many columns so when the column amount is 3/3 I want to create a new row so all is nice and tidy.

How do I solve this?

My idea was to add a number to each column and when the maximum number is reached, there will be a new row.

That code doesn't work. I just want to show the idea.

{% set x = 33.33 %}
{% set y = 66.66 %}

{% for block in entry.this %}
  {% if x + y = 100 %}
{% endif %}
    {# content #}
  {% if x + y = 100 %}
{% endif %}

{% endfor %}

If I can get all variables and add them up it should be possible. But how do I get the variables from each iteration.

Anybody know what I'm talking about? Other solutions?


texts: How to add a button or format style in Craft 3 CKEditor (rich text field)

texts: I'm looking to customize the CKEditor (rich text field) to restrict my client to only these buttons: h2, p, bold, italic, underline, link & unordered list.


texts: How to allow Asset removal in the Control Panel for an Entry

texts:
I've installed Craft Personal 2.5.2763, and have set up my own simple blog.

For each Entry in the Blog Channel, I've set up an Asset Field, which is used for the header image displayed on the blog entry template.

I'd like this Asset field to be optional, as I'll be displaying a default image if one isn't defined in the Control Panel.

Adding an image to the field works great, but I'm seemingly unable to remove it once it has been assigned and saved when I go to edit the Entry and click the "Remove" icon.

When clicking the Remove icon, The image disappears from the CP edit page as you'd expect, but when clicking "Save", it seems the removal of that image is not actually being saved, as it is still there when I go back in to edit the Entry.

UPDATE: I've also found this issue on a normal Text field too. If you set the Text field to some data, save, then go back to edit, delete all text, save, then the data is not removed and the original data remains.

Am I doing something wrong, or is this a bug?

Thanks in advance for any help.


texts: Data Model to Accommodate Statutory Text?

texts:
I am planning to build a searchable database of statutory text, and am wondering what would be the best way to model my data for ease of linking spot citations and related text.

The statutes are generally divided into articles (Art. 1, Art. 2, Art 2-1, Art. 3, et seq.), and within a given article there may be cross-references to other articles of the same statute, or to other articles of different statutes. In other words, Sample Act Art. 99 could contain a reference to Sample Act Arts. 120 and 121, or sometimes an even more detailed cross-reference such as to Sample Act Art. 122, paragraph 1; additionally, Sample Act Art. 99 might also reference Example Law Art. 1.

I would like to pull all cross-references and present the resultant content in a tooltip for the convenience of the reader.

It seems like the easiest way to handle the cross-references would be an Entries field (or perhaps a custom plugin to find the relevant linked content, if we're ambitious). Each individual statute would be a Channel, and then each article of the statute would be an entry in the Channel — perhaps to be organized as a Structure to accommodate the weird sort order that gets created when using article numbering like 1, 2, 2-1, 3.... That seems workable from a Twig templating perspective, but the profusion of 100-150 Channels that would follow from this sort of data model is daunting. I think it would be tough to try to manage so many Channels within the parameters of the CraftCMS UI.

Anyone got any other ideas?


texts:
I'm using this support article as a guide and I'm stuck on what I'm doing wrong.

I have an "events" section, and I would like to use a different template for one the entries.  I've created a new entry type in the "events" section and gave it the handle "summerpreview."  I created a template in the "events" subfolder: "_types" entitled: "summerpreview.html."  That template uses the include tag:

{% include "events/_types/" ~ summerpreview.html %}

I've created an entry inside the "events" section using the "summer preview" entry type and gave it the slug of "summerpreview."

What am I missing here?  The entry pulls using the default "events" template and not the "summerpreview."  What do I need to do for this event to use "summerpreview" template?


texts:
Is it possible to use the Mailgun SDK with Craft at this point?

If not, is it OK to just the composer autoloader as a second autoloader (I'm about to test it, I'm just curious whether it's kosher or there's a different way of doing it that doesn't involve writing another plugin)?


texts: How can I get a specific product via plugin?

texts:
I am able to inspect my cart using commerce_orders.onOrderComplete.

Next I loop through each line item & check for a specific product type. I need to be able to get the specific product, as there are attributes (values) within that product that I am saving to my plugin's records.

For example, if a user purchases "My Product", "My Product" has attributes that include things like "Follow-Up Meetings Qty" Where the admin is allowed to choose the number of meetings are included with "My Product".

Here is what I have that is close, I am stumbling getting the correct criteria model back. I know I'm not working with an entry, so I need to use the purchasable element type.

craft()->on('commerce_orders.onOrderComplete', function (Event $event) {
    user = $event->params['order']->getCustomer()->getUser();
    $orderNumber = $event->params['order']->number;

    foreach ($event->params['order']->lineItems as $item) {
        if ($item->snapshot['product']['typeId'] == 123) {
             $productId = $item->snapshot['id'];

            // Get order details.
            switch ($productId) {
                case 456:
                    error_log('---- My Product Was Purchased ----');
                    error_log('user id: ' . $user->id);
                    error_log('order number: ' . $orderNumber);
                    error_log('product id: ' . $productId);

                    // Get the specific product that was purchased.
                    $criteria = craft()->commerce_purchasables->getCriteria(ElementType::Purchasable);
                    $criteria->limit = 1;

                    ...

                    $products = $criteria->find();

                    if ($products) {
                        foreach ($products as $product) {
                          // Access the products' attributes
                          // $product->meetings_qty  (3)
                          // $product->foo_qty  (2)
                          // $product->bar_qty

                          ...

                          // Save the values to my plugin record.
                        }
                    } else {
                        error_log('no products found that match criteria!');
                    }

                break;
                ...
            }
        }
    }
});

Thank you for any suggestions!

EDIT

Thank you Brad!

Here is what the solution looks like after I removed the over-complication "stuff". Hope this helps anyone who comes across this thread.

craft()->on('commerce_orders.onOrderComplete', function (Event $event) {
        $user = $event->params['order']->getCustomer()->getUser();
        $orderNumber = $event->params['order']->number;

        foreach ($event->params['order']->lineItems as $item) {
            error_log('User id: ' . $user->id);
            error_log('Order number: ' . $orderNumber);
            error_log('Product title: ' . $item->purchasable->title);
            error_log('Product id: ' . $item->purchasable->id);
            error_log('Meetings qty: ' . $item->purchasable->product->myFieldHandle);

            ...
            do some other stuff...
            ...
            Save the record.
        }
});


texts: Demo repo for an Adjuster module for Commerce 2?

texts:
Would it be possible for someone to create a demo of a barebones Adjuster module, similar to https://github.com/cliveportman/craftcommerce-adjuster but for Commerce 2?

I'm trying to follow the docs but can't piece everything together.... basically just looking for the most basic module possible for something that adjust the prices of an item in the cart.


texts: Good way to handle multisite fallback templates

texts:
So I've got a multisite going on.

For most of the sites, most of the time, they'll be using the same templates. But I want a good way to handle siteX needing one template to be different from the other sites.

For example, when going to siteX.com/news, I'd like for the template served to be siteX/news.html if it exists, otherwise default/news.html.

I know I could change the template path in the DB, but I'd rather keep it in the code for development/deployment simplicity.

I think I could could create custom routes, but I'd rather not create a route for every section.

At the moment I'm doing this by creating a root/news.html file, which just says

{% include [currentSite.handle ~ '/news', 'default/news'] %}

but it'd be nice to not have to do this for every template I create. It also seems inefficient to do this on a template level (though I don't actually know this to be true).

So the questions are:

(How) can I overwrite Craft's template resolver to do what I want?
Is this the best way to go about this?

Thanks!


texts:
We have a site using Sprig and Snaptcha. One of our forms is always returning a 400 error "Unable to verify your data submission" which is usually a CSRF issue but thought Sprig takes care of CSRF?
The only solution seems to be disabled CSRF validation so suppose question is:

if we are using Snaptcha on POST form submissions would that be sufficient (eg is CSRF needed), and
any thoughts why sprig might be generating or submitting an incorrect CSRF token?

Cheers
Cole


texts:
I have a plugin that saves users into a registration group like:

 if (craft()->request->isSiteRequest()) {
  //etc
  $groupId = '1';
  craft()->userGroups->assignUserToGroups($user->id, $groupId);
}

However if i listen for the user save event for the control panel:

if (craft()->request->isCpRequest()) {
  //etc
  $groupId = '1';
  craft()->userGroups->assignUserToGroups($user->id, $groupId);
}

This doesnt work. I also tried passing an array as groupId(s) but the group permission never gets ticked.

Is there another way of assigning a new user saved in the back end to a specific permission group?


texts: Eager Loading Users Returning "Array to String Conversion" Error

texts:
I am trying to eager load users in a specific group to reduce queries. I've tried this:

                {% set designers = craft.users({
                    group: 'designers',
                    with: [
                            'userAgencyName',
                            'userAgencyUrl',
                            'userFreelancerAgency',
                            'userDescriptionServices',
                            'userBudget',
                            'userCity',
                            'userStateProvince'
                            ]
                }) %}

This consists of 5 user text fields and 2 user category fields. Although it's returning the array to string conversion error.

The loop is setup like this:

    {% paginate designers.limit(7) as designers %}

    {# Loop through Designers #}
    {% for designer in designers %}

{{ designer.userAgencyName }}

                {% for category in designer.userFreelancerAgency %}
                 {{ category }}
                {% endfor %}

                {% for category in designer.userBudget %}
                {% if category %}

                Budgets: {{ category }}

                {% endif %}
                {% endfor %}
                {% if designer.userCity | length %}

{{ designer.userCity }}, {{ designer.userStateProvince }}

                {% endif %}

{% if designer.userDescriptionServices %}{{ designer.userDescriptionServices }}{% endif %}

   {% endfor %}

Thanks in advance for any help you can give!


texts:
I'm working on a custom Craft 3 site, and I need to be able to configure the element indexes within the control panel for a few of my custom EntryTypes. There's two particular things I'd like to control (which may merit two separate answers):

I'd like to be add custom columns to the table. These columns do not correspond to fields on the Entry, but they're more of a "computed property" if that makes sense.
I'd also like to modify the query that is ran for fetching those entries. In my particular case, some entries should not show up based on which user is logged in, and some custom business logic.

Is there a way to do this? My current investigation with ElementIndexesController::actionGetElements (the API call that the CP appears to be making) hasn't panned out: I don't see any global events or view hooks that I could wire into.


texts: Form in Front End Template Reference Plugin for LDAP

texts:
I am a Craft newbie, and I'm currently making a few custom templates, learning Twig, etc.
My question is: in including a form in my template code, how would the form be coded (Twig or HTML)?  Is there a good tutorial/reference on forms used in this way?  Also, how would I reference my php code (which is within my plugin)?

The form will be an log-in authentication, and the plugin contains the code to verify that the user exists in Active Directory (LDAP).

I'll sketch out the way my website is laid out.  There are only a handful of users who actually log in to CraftCMS in order to make changes to content on the website.
However, the login form I'm making here is not to log in to Craft, but to gain access to one page of the website.  I will need to create a form page template and have it submit to my php code (plugin) somehow.


texts: Structure a site with multiple locations with categories, structure or "multisite"?

texts:
I'm proposing to use Craft for a company that runs multiple golf courses. Along with some general pages for the company as a whole, each location (course) is to have it's own microsite, for want of a better phrase. At the moment each location will have the same pages (but that could change in the future), along with a news section.

I think I can achieve this with a combination of categories and structures, but I'd be keen to know if anyone has any other ideas. (Possibly "multisite" with locals?)

My thoughts are:

Homepage - Single
Global About - Single
Global Golf Pros - Channel
Locations - Structure with individual entry types for each sub page
Global Contact Us - Single
News (there's no requirement for this to be global at the moment, but creating multiple news channels seems a little painful) - Channel (with category filed to scope to each location)

Within the Location's channel I can then use relationships for each location's Golf Pros (from the Global Golf Pros channel) and list news articles via twig craft.entries.section('news').categories('location-x') and a slightly elongated Entry URL Format "locations/{location.first.slug}/news/{slug}"

Sometimes a picture is worth a 1,000 words, so here goes.

I feel a little like I'm mixing the use of categories and structures though.

Any thought would be much appreciated!

Thanks in advance,

Tom


texts: dev- branch plugin forks being prompted for update

texts:
I'm currently using a fork of a plugin for my site, and using a "dev-[branch-name]" version specification in the composer "require" block, with a "vcs" repository definition for the fork location on github - basically looks like:
"repositories": [
  {
    "type": "vcs",
    "url": "https://github.com/[forked-account/plugin-name]"
  }
],
"require": {
  "[original-account/plugin-name]": "dev-branch-name"
  ...
}
...

This worked fine for several months, but I'm suddenly now seeing a prompt to update to the latest version of the plugin on the author's "master" branch when running Craft update.  Has something changed with the requirements for the composer file version declarations for Craft to respect the "dev-" branch version as the preferred plugin version?


texts: Find entries from related section after certain date

texts:
Does anyone know how to achieve the following in Twig with Craft 3:

My sections
locations and trainings.

I want to find all the entries from locations which has a relation to trainings and a datetime field value from trainings has to be after now.


texts: Customize markup of email select field in Sprout Forms

texts:
I'm trying to customize the markup of an email select field in Sprout Forms, however, when I customize the markup with Custom HTML, as specified in the documentation, it outputs the actual value rather than purging it to hide them from spam bots. I just need to know what I should include in the options to purge these. Here is the code I've been using.

{% set recipient = form.getField('emailRecipient') %}
<select name="fields[{{ recipient.handle }}]">
  {% for option in recipient.settings.options %}
  <option value="{{ option.value }}" {% if option.value == value.value %}selected{% endif %}>{{ option.label }}</option>
  {% endfor %}
</select>

Any help would be greatly appreciated!

Thanks.


texts: How to get section content from another site with multisite setting

texts:
I have a multisite on Craft 3 and I was wondering how to get section content from another site? Let's say I'm on a default site and I want to get contact content from site with handle siteA?

Can this be done?


texts: How to update cart.lineItems while specifying HTTP cache headers?

texts:
I use the following cache system, specified in the header of all pages:

{% set expiry = now|date_modify('+1 day') %}
{% header "Cache-Control: max-age=" ~ expiry.timestamp %}
{% header "Pragma: cache" %}
{% header "Expires: " ~ expiry|date('D, d M Y H:i:s', 'GMT') ~ " GMT" %}

This does not coexist properly with the variable {{ cart.lineItems|length }} which displays on each page the number of products currently in the cart.

When I update the basket and go back to a previously visited pages, the cart is not up to updated and retains the value displayed during the previous visit.

To be more specify: I do not use the {% cache %} tags on the template part which displays the shopping cart.


texts: Search products and entries with pagination

texts:
Is there any way of searching both entries and products at the same time? Wanting a single search on the site which will return all entries and products containing the searched for phrase.

Looked at combining the results from craft.entries.search() and craft.products.search() but this stops us from using pagination which we would like to have. Anybody got a solution or suggestions?

Would prefer not to split into 2 search pages if possible. Thank you.


texts: How to display entries relevent to date assigned

texts:
I am creating a website for not-for-profit organization that help victum of domestic violence. I have a page called Event which display all fund raising events under each month.

I have setup Date/Time field and 12 months tabs and want to know how to display the entries for each month. For example I assign two entries for Feb and when I click on Feb tab, the entries will display.

Here is the sample code I wrote and copied Marion Newlevant's suggestion but when I tested it does not work. Any ideas?

Here is what my html structure to display the entries for each month.

    = '~startDate, '< '~endDate])
    %}

        {% for asset in entry.eventThumbnail %}
          {% if asset in entry.eventThumbnail %}

          {% else %}

          {% endif %}
        {% endfor %}

{{ entry.title }}

        {{ entry.subtitle }}

{{ entry.eventBlurp}}

        {% for block in entry.eventOrganiser %}
          {% if block.type == "eventDate" %}

              Buy Ticket

{{ block.ticketLeftover }} / {{ block.ticketAvail }} tickets left

          {% endif %}
        {% endfor %}

  {% endfor %}


texts: How do I nest multiple templates while keeping a wrapper for some pages

texts:
I'm trying to figure out how to nest 3 templates and have them inherit the blocks. How can I sometimes reference the child.html when I need a wrapper and sometimes not reference it. Maybe I'm trying to do this the wrong way? Thank you for your feedback.

parent.html

{% block contentBlock %}
{% endblock %}

child.html

<div>
{% extends "parent" %}
{% block content %}
</div>

child-child.html

{% extends "child" %}
{{ title }}

child2.html

{% extends "parent.html" %}
{% block contentBlock %}
{{ title }}


texts: Does "verify email addresses?" have to be enabled in order to fire the users.onActivateUser event?

texts:
I'm trying to listen for an event when users create new accounts. I have the following code in my init() function in my main plugin class:

craft()->on('users.activateUser', function(Event $event) {
    error_log("user activated");
});

This isn't firing when new users register on the site and I'm wondering if this has to do with the "Verify email addresses?" users setting. I'm not requiring users to verify their email addresses. Does that setting have to be checked in order to trigger that event? If so, is there a different event to listen for?


texts: German special characters like umlauts (ä, ö, ü) are not converted correctly with convertFilenamesToAscii

texts: Filenames with German special characters are not converted correctly with convertFilenamesToAscii, e.g. ä, ö, ü are converted in a, o, u in contrast to ae, oe, ue in slugs with limitAutoSlugsToAscii.


texts: Sending activation emails to all pending users

texts:
I have around 200 hundred users for an intranet setup on the Craft Users section all as pending status. Is there a way to send an activation email en-mass to all pending users? Rather than having to run through each user one at a time.

The system is set to change over and each user will need to verify their account and set their password, but they've been added to the system in advance and need to be sent an activation email out of hours so that they Intranet system changes overnight and they have an email waiting for them the next day they step into the office.


texts:
Is there a way to order the Craft Element-API results by the category title?

I'm just getting the error

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

The "hostingCompany" field is a category field.

'hostings.json' => [
        'elementType' => Entry::class,
        'criteria' => [
            'section'   => 'hostings',
            'orderBy' => 'hostingCompany desc'
        ],
        'paginate' => true,
        'transformer' => function(Entry $entry) {

            return [
                'hostingDomain'  => $entry->hostingDomain,
                'hostingCompany' => (string)$entry->hostingCompany[0],
                'url'            => $entry->url,
            ];
        },
    ],

Updated error message:

PHP Warning 'yii\base\ErrorException' with message 'Header may not contain more than a single header, new line detected'
in /Applications/AMPPS/www/crm.local/vendor/yiisoft/yii2/web/Response.php:380
Stack trace:
0 /Applications/AMPPS/www/crm.local/vendor/craftcms/cms/src/web/ErrorHandler.php(81): yii\base\ErrorHandler->handleError(2, 'Header may not ...', '/Applications/A...', 380)
1 [internal function]: craft\web\ErrorHandler->handleError(2, 'Header may not ...', '/Applications/A...', 380, Array)
2 /Applications/AMPPS/www/crm.local/vendor/yiisoft/yii2/web/Response.php(380): header('HTTP/1.1 404 SQ...')
3 /Applications/AMPPS/www/crm.local/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
4 /Applications/AMPPS/www/crm.local/vendor/yiisoft/yii2/base/Application.php(392): yii\web\Response->send()
5 /Applications/AMPPS/www/crm.local/web/index.php(21): yii\base\Application->run()
6 {main}


texts: Entry translation differences Craft 2 and Craft 3

texts:
In the middle of a Craft 3 build and the client has requested locales like their Craft 2 multilingual site. I am confused by Craft 3 localisation.
It appears I have to add a site as a language before I can localise/translate any content?

In Craft 2 the adding of translated content could be done directly in the entry via the panel above the slug field - here all the locales for Craft 2 would appear. (On the right in desktop use)

But despite options of Translation method, site, group, language the old method of swapping between entry content language within the entry on the right hand panel is not there. This makes it difficult to see / swap to what has been translated.  It appears changing language is done in the list view of entries. Am I missing something :( ?

Here is a shot of Craft 2:

Here is a shot of Craft 3:


texts: How to optimize nested reverse relations?

texts:
I have the following situation:

A section called "membership" and a section called "member".
Within the "member" section I can choose one or more memberships.
Now I'd like to display all memberships with the reverse related members.

The output would look something like this:

membership 1
    member 1, member 2, member 3

membership 2
    member 2, member 4

membership 3
    member 1, member 5

How would I do this?

I have the following code, but it's very slow:

{#

    Get all membership entries

#}
{% set entries = craft.entries({
    section: 'membership',
    order: 'cf_membershipShorthand',
}) %}

{% for entry in entries %}

{% if entry.cf_membershipShorthand %}{{ entry.cf_membershipShorthand }} – {% endif %}{{ entry.title }}

    {#

        Get the related members entries

    #}
    {% set members = craft.entries({
            section: 'member',
            relatedTo: entry,
        })
    %}
    {% if members|length %}
        {% for member in members %}
            {% set image = member.cf_ma_asset[0] ?? null %}
            {% if image|length %}
                {% set imageParams = { width: 30, height: 30 } %}

            {% endif %}
        {% endfor %}
    {% endif %}
{% endfor %}

I even tried to eager load the related members entries, but, to my surprise, that even added queries.

I must be on the wrong path. Could anyone enlighten me?

Thanks

Update to my question:
I know how to eager load the related entries:

{% set member = craft.entries({
        section: 'member',
        relatedTo: entry,
        with: [
            ['cf_ma_asset', { withTransforms: [{ width: 30, height: 30 }] }],
        ]
    })
%}

To my surprise that adds queries, but is much faster...


texts: Craft 3: 500 Internal Server Error when trying to install on server

texts:
For the last 3 days i've been trying to install Craft CMS 3 on my server.

I'm using 1&1 internet, have FTP uploaded all the files, changed the permissions for the folders and files to the right level and made sure everything is pointing in the right place.

It's worth noting i've installed Craft CMS 2 on this exact server for years with no issues at all. I also successfully installed Craft CMS 3 locally with no issues.

Going to mydomainname.com shows a craft error page with

HTTP 503 – Service Unavailable - craft\web\ServiceUnavailableHttpException

throw new ServiceUnavailableHttpException();

Going to /admin/install or index.php?p=admin doesn't work it just gives me an Apache Error screen with 500 Internal Server Error.

I've also tried using ssh and attempted to install composer but have been unsuccessful at that as my server doesn't seem to want to allow me to.

I need to get a website live asap and don't really know what I can do next! I'm not hugely experienced with servers etc.

Any advice much appreciated.


texts: Can I manage/change the default flash message text?

texts:
I am looking to customise the default flash message text for certain behaviours but cannot seem to find any reference to them in the code or control panel - does this exist anywhere? And could it be made editable in the CP?

I know I could do something like this but it feels hacky:

{% if craft.app.session.getFlash('notice') == 'User registered.' %}
  {% do craft.app.session.setFlash('notice', 'User registered - please check your email to activate your account.') %}
{% endif %}

Thanks.


texts: Plugin development - Adding Foundation 5 CSS changes Craft CMS control panel

texts:
I am trying to embed a Google Map widget as a field in Craft. I am doing plugin development to achieve it.

Adding a foundation 5 css in a PluginName_FieldType.php file into the getInputHtml() function results in changes is Craft Control panel.

craft()->templates->includeCssResource('pluginhandle/foundation.css');

I apologise if it is something silly. I am a newbie to Craft.


texts:
Has anyone been successful using Satis for composer repo(s) with Craft plugins? I have a repo set up with artifacts, that are posted as a public composer repo in the network. It finds the plugins and downloads, but for some reason I keep getting the following error whenever I try to do composer update:

[craft\composer\InvalidPluginException]
  Couldn't install vendor/plugin: Unable to determine the base path

It works if I do a local path and pull it in that way.


texts:
Is it possible to upload assets into the folders listed in the asset section on the server manually/directly? And then "sync up" the system so the ui sees these?

Used to be able to do this in expression engine via a sync button and i don't see how to do that here, but perhaps im missing the trick?

Thanks


texts: Output the contents of an instructions field within a Matrix block

texts:
As the title suggests, i'm trying to output the contents of a default instructions field within a Matrix block.  I'm sure it's doable but not sure where to start?

Thanks

Martin


texts:
I'm searching for a option to remove all unused images every minute.

The images I use are for Craft Commerce.


texts:
I am not sure if anybody has come across this, but after clicking "Settings" in the Admin Center all of my "Pages" entries are un-editable.  When I click to edit them, all that shows is the title, the "Current" button, and the "Save" button with the drop down disabled.

Here is what I get when I click on a page to edit:


texts:
When trying to save content under the Settings > Sections I get no obvious (fatal) errors in the log files or in the debug bar, yet nothing saves and everything reverts to what it was on page load.

I'm running this in a docker set up, and I've attempted to "fix" file permissions settings based on this https://craftcms.com/docs/3.x/installation.html#step-2-set-the-file-permissions - all files/folders are owned by the host system.
This is the only area of the admin panel that I can't edit.
NOTE: this is a duplicated site from another working install. So there have been a lot of changes to the files/folders and database. This seems to be the last sticking point after this duplication.
What can I try to get this working?


texts: In the CP, How to make images bigger when the users select images?

texts: In the Control Panel, when users are selecting an image for the asset field, the thumbnails are too small in the popping up image modal. Is there any way to make the images bigger?


texts:
I'm moving a craft install from a development to production server and am getting this error:

ERROR ERROR
Craft can’t connect to the database with the credentials in craft/config/db.php.

I've triple checked the db credentials and permissions and everything is correct. Here's my db.php file:

<?php

// uncommenting this gives me a 'connected okay' so I know that the credentials are correct.
// if ($con=mysqli_connect("localhost","thandtho_db","*********","thandtho_production")) // {
//  die('connected okay');
// } else {
//  die('couldn\'t connect');
// }

/**
 * Database Configuration
 *
 * All of your system's database configuration settings go in here.
 * You can see a list of the default settings in craft/app/etc/config/defaults/db.php
 */

// Import your local config settings
require( 'config.local.php' );

return array(
    '*'=> array(
        // Database Info
        'tablePrefix' => 'craft',
    // Production Domain
    '9thandthomas.com' => array(
        'server' => 'localhost',
        'user' => 'thandtho_db',
        'password' => '***********',
        'database' => 'thandtho_production'
    ),
    ),
    // Dev
    '9thandthomas.transomco.com' => array(
        'server' => 'localhost',
        'user' => 'ninththomas_dev',
        'password' => '4iJoi58@',
        'database' => 'ninththomas_dev'
    ),
    // Local
    // Needs to be placed after production since subdomain
    // is similar to production domain name.
    $localConfig['envUrl'] =>  array (
        'server' => $localDatabase['server'],
        'user' => $localDatabase['user'],
        'password' => $localDatabase['password'],
        'database' => $localDatabase['database'],
    )
);

************************** ANSWER **************************

I moved the database details from beneath the * and it worked.

db.php now looks like this:

<?php
/**
 * Database Configuration
 *
 * All of your system's database configuration settings go in here.
 * You can see a list of the default settings in craft/app/etc/config/defaults/db.php
 */

// Import your local config settings
require( 'config.local.php' );

return array(
    '*'=> array(
        // Database Info
        'tablePrefix' => 'craft',
    ),
    // Production Domain
    '9thandthomas.com' => array(
        'server' => 'localhost',
        'user' => 'thandtho_db',
        'password' => 'wR39fy2!k',
        'database' => 'thandtho_production'
    ),
    // Dev
    '9thandthomas.transomco.com' => array(
        'server' => 'localhost',
        'user' => 'ninththomas_dev',
        'password' => '4iJoi58@',
        'database' => 'ninththomas_dev'
    ),
    // Local
    // Needs to be placed after production since subdomain
    // is similar to production domain name.
    $localConfig['envUrl'] =>  array (
        'server' => $localDatabase['server'],
        'user' => $localDatabase['user'],
        'password' => $localDatabase['password'],
        'database' => $localDatabase['database'],
    )
);


texts: I'd like to show a 'Jobs' link in my navigation only if the Jobs page is enabled. Is there a way for craft to detect if the page is enabled, and show a div?


texts: Refused to display/connect when previewing entry on multi-site setup

texts:
I run a multi-site setup with four sites; one on unicorn.com and one on all-your-base.com.

The way Craft CMS licensing works, you can run multiple sites on different domains on the same license/install, but you have to edit all the sites from just one domain - unicorn.com in this case.

When I click "live preview", from unicorn.com all I see is a sad pixelated face and a message saying "all-your-base.com refused to connect."

Console says: "Refused to display 'https://all-your-base.com/...' in a frame because it set X-Frame-Options to 'sameorigin'


texts: I used to be able to resize and select align attributes for images in Rich Text and now that feature is completely gone since my last update. Do I need to change settings or has that feature actually been removed?


texts:
For the last weeks I've tried installing composer, but without any luck. I've really tried aaa  looott, and how frustrating it is, it's just not working with SSLv3 for some strange reason.
This was the thread I opened: Unable to get composer running to install CraftCMS

So I had to give up, at least for now, to be able to use Composer and had to decide to switch to manually setup craft, which I just did. But now I'm having a problem installing plugins. The Plugin store isn't working and it probably uses composer in the back (?). I've found a question here about how to manually install plugins without the plugin store, but... it also uses composer. Which isn't working here.

Is there another way of installing plugins manually?


texts: Twig function to load templates into variable?

texts:
I'm trying to figure out how to load a template file and pass it as a variable to another template file while it is being included. In some sense I want to do something like this:

{% include 'component/footer', with 'component/nav' %}

I know I can't do that directly, but in the twig documentation there is an example showing this:

$template = $twig->load('some_template.twig');
$twig->display('template.twig', array('template' => $template));

Is it possible to do the same thing with Craft's twig support?


texts: MVC - Should these be seperate controllers/models etc

texts:
I hope this is the right place to post this, it's more a question on MVC for plugin development.

I'm developing a plugin to extend SproutForms to add users to Campaign Monitor lists. So far I've got the interface where the user can submit their API key and List ID. I then use these to pull in information about the list and add it to the db in pluginname_forms.

Now, I also want to pull in the custom fields for that list and store them in the pluginname_formFields table.

From an MVC point of view, should I keep this in the service that deals with the list data or create a new service which deals with the custom fields data?


texts:
I have a problem with a pair of cache tags refusing to bust the cache when a new entry is added.  The cache works well otherwise.
This is the template code I'm using... it's fairly complex as we're using it to filter products in an ecommerce site.

{% cache %}
  {% set products = craft.entries.section('products').relatedTo(entry).find({limit: 1000}) %}
  {% include 'shop/partials/_product_list' with { products : products } %}
{% endcache %}

This is the include.

{% for product in products %}
    {% set cat_classes = '' %}

    {% for cat in product.category %}
        {% set cat_classes = cat_classes ~ ' ' ~ cat.slug %}
    {% endfor %}

    {% for cat in product.collection %}
        {% set cat_classes = cat_classes ~ ' ' ~ cat.slug %}
    {% endfor %}

    {% for range in craft.entries.find({limit: 1000, section: 'priceRange'}) %}
        {% if product.price >= range.priceFrom and product.price <= range.priceTo %}
            {% set cat_classes = cat_classes ~ ' ' ~ range.slug %}
        {% endif %}
    {% endfor %}

    {% for days in craft.entries.find({limit: 1000, section: 'leadInTimes'}) %}
        {% if product.leadInTime >= days.leadInFromDays and product.leadInTime <= days.leadInToDays %}
            {% set cat_classes = cat_classes ~ ' ' ~ days.slug %}
        {% endif %}
    {% endfor %}

    {% if product.canBePurchasedOnline %}
        {% set cat_classes = cat_classes ~ ' buy-online' %}
    {% else %}
        {% set cat_classes = cat_classes ~ ' special-order' %}
    {% endif %}

        <picture>
            ...
        </picture>

{{ product.title }}

            £{{ product.price }}

{% endfor %}

If anyone has any ideas I'd be grateful!


texts: Back-up doesn't work in Craft CMS 3 on MAMP locally

texts:
I installed Craft CMS 3.0.1 locally on MAMP (Apache/PHP7.0.22), but when I want to do a backup of the database it says:
"There was a problem backing up your database. Please check the Craft logs. Back-up van database".
I cound not find any logs that pin pointed the problem. How does this happen? Thanks in advance.


texts: Do I need 2 licenses for staging and production

texts: Or is one pro license enough? We're running a stage environment and a production environment for the same website. Thoughts?


texts: How can I work with related entries within a Matrix in a plug in?

texts:
I have a Matrix field named "skillLevels" with a single block type.
Each row has 2 fields, "skillName" and "skillLevel"

skillName is a relationship to another entry (Skills)
skillLevel is a simple integer.

I am building a custom plugin which takes post data from a form.
The form contains an entry ID ($groupId), a skill name and a value to use to modify the level of that skill.

$groupEntry = craft()->entries->getEntryById($groupId);

    $skillLevels = $groupEntry->skillLevels;

    foreach($skillLevels as $skill){
       $skillLevel = $skill->skillLevel; // outputs the skill level
       $skillName = $skill->skillName; // this doesn't work
    }

$skill->$skillLevel gives me the integer stored in that field.
But $skill->skillLevel does not gives me a model. I then tried using $skill->skillLevel->id but still no luck.

How can I look through the Matrix rows to find the row that matches the skill name coming from the form Post data?


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

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


texts: Global nav with dynamic links across multiple sites

texts:
We are currently working on using Craft to build out new versions of our site (in-house) and we have multiple sites that will share a global nav. Is there a way for one site to access the data in another site to update the global nav dynamically? I'm not sure if it's possible but I also know Craft is pretty magical.

The parent domain link and child domain link will hardly never change so that can stay static content; more so wondering about accessing the data in the child domain from parent/sibling sites.

example structure

parent domain link
  |-- child domain link
  |   |_
  |     |-- dynamic links
  |     |-- dynamic links
  |     |-- dynamic links
  |
  |-- child domainlink
  |   |_
  |     |-- dynamic links
  |     |-- dynamic links
  |     |-- dynamic links
  |
  |-- child domain link
     |_
       |-- dynamic links
       |-- dynamic links
       |-- dynamic links


texts: Craft keeps displaying session timeout prompt

texts:
For some reason the admin keeps popping up the session timeout box, it seems after about a minute, even thought I can clearly see in my sessions that they have ages until expiry.

See -> https://www.dropbox.com/s/egfg019cruv3uzn/Screenshot%202015-09-11%2009.39.21.png?dl=0

Also strangely when I refresh the page I'm still logged in. What would be causing this. The site is running on nginx if that would make any difference.


texts:
I'm having some trouble passing CSRF-tokens in my js-File in Craft 3.

I'm setting the values in my template like so:

<script type="text/javascript">
    window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName }}";
    window.csrfTokenValue = "{{ craft.app.request.csrfToken }}";
</script>

and call them in my .js-file:

var data = {id: 100 };
    data[window.csrfTokenName] = window.csrfTokenValue;
    $.ajax({
        type: 'POST',
        url: href,
        data: data,
        success: function(result){
        },
        error: function(){
        }
    });

before i set the csrf tokens, the server returned an error 400 – bad request – as you would expect.
now i'm getting a 500 internal server error.
What am I doing wrong?

The site works perfect without the ajax-call so I don't think there's an issue with my templates. Tell me if you need to see more of my code.


texts: How to redirect a url with a query to one that does not have a query

texts:
I'm using Redirect Manager (https://github.com/rkingon/Craft-Plugin--Redirect-Manager) and I"m trying to redirect:
www.website.com/?post_type=testimonials

To:
www.website.com/about-us

I've tried the following regex rules with no success (hashes are needed for regex in redirect manager):

#^\?post_type=testimonials#

#^\?post_type=testimonials$#

#post_type=testimonials$#

All of them just stay on the homepage with the query appended when accessing the url. Any ideas on how to fix it or better ways of achieving this would be appreciated.


texts:
I've got an even notifier plugin I have been working on for a specific client project. Sending an email to a single address works fine, but when I loop through a table containing email addresses it is sending duplicate addresses.

I have a global table field (adminEmails) which has two columns, one for a name and the other for an email address.

          $adminGlobal = craft()->globals->getSetByHandle('admin');
          foreach($adminGlobal->adminEmails as $key => $admin){
            $email->toEmail = $admin['emailAddress'];
            $body .= "Manager ".$manager->fullName." has submitted an event for approval.\n\n";
            $body .= "Start Date & Time: ".$entry->eventStartDate->format('m/d/Y g:i A'). "\n\n";
            $body .= "House: ".$house->houseName."\n\n";
            $body .= "School: ".$college->collegeName."\n\n";
            $body .= $entry->url;
            $email->body = $body;
            if($email->toEmail != ""){
              craft()->email->sendEmail($email);
            }
          }

I have been testing with two email addresses and both addresses receive the same email twice. Not sure what could be causing this. I tried creating a new email model object inside each foreach loop but that didn't help either. Any ideas what's happening here?

EDIT:

If I dump $admin you see the following,

array
(
'col1' => 'John Doe'
'col2' => 'some.email@gmail.com'
'adminName' => 'John Doe'
'emailAddress' => 'some.email@gmail.com'
) 0 array
(
'col1' => 'Andrew Clinton'
'col2' => 'some.email@anecka.com'
'adminName' => 'Andrew Clinton'
'emailAddress' => 'some.email@anecka.com'
) 1

This is what I was expecting..so why is it sending the same email twice to both addresses?


texts:
I'd like to run the entry.body content through some PHP functions before the template outputs it, there probably two approaches to this:

Create a twig function via Plug (if possible) and use that in template like:

{{ MyFunction( entry.body ) }}

Have function automatically grab the "body" of the current page, run through functions, and update it before template runs it. I'd prefer this method although but have no clue how to go about it.

What would be the best approach -- and does anyone have any pointers / samples on how it'd be done? I've been digging through documentation but am struggling to find how to get the current entry.body through a plugin, or how to update it (just for the page rendering + template, not in database.)


texts:
My task queue (is that what it's called?) is filled with literally hundreds of "Deleting Stale Template Caches" and every day there seem to be new ones. Along there are also resaving entries tasks and updating URIs.

Because of the amount of tasks, they don't seem to be going down AT ALL. What's the suggestion here?


texts:
So i am developing a site on Mamp Pro locally.
All good.
Its version controlled with github.
When deployed to staging server it was fine initially.
Last Friday deployed again and now i keep getting fatal errors:

    Stack trace:
#0 /home/mywebpath/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
#1 /home/mywebpath/vendor/yiisoft/yii2/web/ErrorHandler.php(135): yii\web\Response->send()
#2 /home/mywebpath/vendor/craftcms/cms/src/web/ErrorHandler.php(156): yii\web\ErrorHandler->renderException(Object(yii\base\ErrorException))
#3 /home/mywebpath/vendor/yiisoft/yii2/base/ErrorHandler.php(262): craft\web\ErrorHandler->renderException(Object(yii\base\ErrorException))
#4 [internal function]: yii\base\ErrorHandler->handleFatalError()
#5 {main}
  thrown in /home/mywebpath/vendor/yiisoft/yii2/web/Response.php on line 366
[02-Jul-2018 20:59:04 UTC] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes) in /home/mywebpath/vendor/composer/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52
[02-Jul-2018 20:59:04 UTC] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 32768 bytes) in /home/mywebpath/vendor/craftcms/cms/src/i18n/Locale.php on line 822
[02-Jul-2018 20:59:04 UTC] PHP Fatal error:  Uncaught yii\web\HeadersAlreadySentException: Headers already sent. in /home/mywebpath/vendor/yiisoft/yii2/web/Response.php:366

I am going to do a vanilla setup on the server just to test but if anyone has any ideas or similar experience do share any resolutions/ideas.
thx


texts: Craft Commerce - Edit Complete Order Address from frontend

texts:
We are trying to give our clients the ability to update an order's shipping address before the order has been actually shipped.

We've created a members area where they can list their orders and access them individually. When in an order, we have a link that loads a specific address form template e.g. /addresses/edit/{{order.shippingAddress.id}} but the address form doesn't load throwing the error Impossible to access an attribute ("id") on a null variable.

This exact same address edit form works fine when loading the address from the craft.commerce.customer.addresses model e.g. addresses/edit/{{ address.id }}. Having a look at the DB, we've found that the address if from the order model doesn't actually exists in the craft_commerce_customers_addresses table which would explain it.

Is there anything we've missed?

Cheers,
Alberto


texts:
I would like to have a custom field on the general settings page where I can enter the meta description for the website. Can this be achieved somehow?

Another way I could think of is to add such a field to a section, the homepage for example, but this solution wouldn't be elegant.


texts: 301 Redirects Appends ?p=original/url/path - how can I remove?

texts:
Whether I'm using the Reroute plugin or plugging it in .htaccess, changing the path elsewhere appends the query in the end. How can I remove?

Redirect 301 /blog/category /blog/archive

Is the line I have in my .htaccess

So if I go to:

http://domain.com/blog/category/category-name

it takes me to:

http://domain.com/blog/archive/category-name?p=blog/category/category-name

What's going on here?


texts: Get a list of countries available for shipping with Ajax in Craft Commerce

texts:
I need to fetch a list countries available for shipping in Craft Commerce.
The problem is that I use decoupled frontend on Nuxt.js and I need fetch it with Ajax call and not with the twig code.
I tried to call it in a Postman but it returns me a 403 - Forbidden error with message "User is not permitted to perform this action".
I couldn't find something about the way of making request through Ajax in Commerce documentation, can you please tell me what I'm doing wrong here?


texts: Module: EVENT_AFTER_SAVE_ELEMENT won't detect changed user group

texts:
Event::on(\craft\services\Elements::class, \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) {
    if ($event->element instanceof \craft\elements\User) {
        $user = Craft::$app->getUsers()->getUserById($event->element->id);
        if ($user->isInGroup('abc')) {
            // Do something
        } else {
            // Do something different
        }
    }
});

I created a C3 module on pluginfactory.io. The code above works just fine in detecting when a user is saved/updated.

For sake of simplicity I have two user groups 1) abc 2) def.

When I uncheck the user from def and check him into abc (or the other way around), and save the user, my code won't register that the user group has changed, but thinks the user is still in the previously selected group. If I re-save the user (without changing groups), suddenly the code sees the correct group.

I assume that despite using EVENT_AFTER_SAVE_ELEMENT, the system still saves the user group change to the db after the Event triggers. Could that be it?

It's weird though, because any other field I pull from the user, e.g. if I change their email, my code is able to pick up the new email on the first save, so why not the change in user group?

Any assistance is greatly appreciated,
cheers!

Edit: Made problem clearer to understand.


texts:
I am at the very early stages of using CractCMS but I'm keen to get off to the correct start, writing notes as I go along etc but I cannot figure this issue out.

I have setup the Multi-Environment Configs to allow me to use, dev, staging and production sites, staging and production appear to work correctly but development site is causing issues.

I know it's something to do with the .env file and

ENVIRONMENT="production"

If I change that to

ENVIRONMENT="dev"

The development site will work.

What I can't understand is, both staging and production work so why not development?

I thought by using db.php and general.php I could do away with .env? Other than this line I can.

Here's my General.php code

<?php

return [
// Global settings
'*' => [
    // Default Week Start Day (0 = Sunday, 1 = Monday...)
    'defaultWeekStartDay' => 1,

    // Enable CSRF Protection (recommended)
    'enableCsrfProtection' => true,

    // Whether "index.php" should be visible in URLs
    'omitScriptNameInUrls' => true,

    // Control Panel trigger word
    'cpTrigger' => 'admin',

    // The secure key Craft will use for hashing and encrypting data
    'securityKey' => '*******************************',
],

// Dev environment settings
'dev' => [

    // Base site URL
    'siteUrl' => null,

    'basePath' => '@webroot/cpresources',

    'baseUrl'  => 'https://mydomain.test',
],

// Staging environment settings
'staging' => [
    // Base site URL
    'siteUrl' => null,

    'basePath' => '@webroot/cpresources',

    'baseUrl'  => 'https://staging.mydomain.co.uk',
],

// Production environment settings
'production' => [
    // Base site URL
    'siteUrl' => null,

    'basePath' => '@webroot/cpresources',

    'baseUrl'  => 'https://mydomain.co.uk',
],
];

Here's my db.php code

<?php

return array(
'*' => array(
    'tablePrefix' => '',
    'driver' => 'mysql',
    'schema' => 'public',
),
'dev' => [
    // Base site URL
    'server' => 'localhost',
    'user' => 'myusername',
    'password' => '*************',
    'database' => 'mydatabasename',
],
'staging' => array(
    'server' => 'localhost',
    'user' => 'myusername',
    'password' => '*************',
    'database' => 'craft_cms_staging',
),
'production' => array(
    'server' => 'localhost',
    'user' => 'myusername',
    'password' => '*',
    'database' => 'craft_cms_production',
),
);

Now before anyone says anything about uploading db.php and general.php to git etc because of passwords, I have put both these files in the .gitignore file. I felt this was the best option but if I'm wrong, please explain?


texts: Display & check-for User Group on public profile

texts:
This two-part question is half an exact duplicate of How do you display a user's User Group? but I'm unable to leave a comment :(

I'm trying to display & check-for the user group a user belongs to on a public profile page. There are coaches and players.

The URL structure is domain.com/coaches/johnnyappleseed

Copying the exact example code given in the original question (link above) seems to just return the User's full name, not the group the user belongs to. What could I be missing?

Also, if johnnyapplseed is a coach, I can still access his profile page by going to domain.com/players/johnnyappleseed which is why I'm trying to check for the usergroup to begin with. Is checking for the usergroup in each player & coach profile template the correct way to do this?

UPDATE: I've attached a screenshot of all the information I think could possibly be relevant. This has to be something simple I'm overlooking!


texts:
I love using the excerpt option in Wygwam (CKEditor). I've looked high and low but as of yet, have been unable to find a way to have an exceprt show short of having a whole second field. I have seen a custom Twig filter running around that would allow to show first paragraph (which I could modify to show whatever) but I like the ease of doing it straight in the WYSIWYG. Anyone have any options? (looking for a solution for a news roll page)

(First P Twig filter)
https://gist.github.com/james2doyle/6629712


texts: Get the Top Authors based on entry counts?

texts: I want to be able to display Top Authors based on their entry counts. Has anyone ever tried doing this?


texts: Is there a way to auto-create a sections Site Settings and propagate when a new site is created?

texts:
My customer will have lots of sections and lots of entries in each, for each site. Over time they will add new language sites.

When a new site is added, there are no sections or entries for it. So we have to then edit each section to set the URL format and template, even though they will be the same for each site.

I would like to make it as easy and quick for the customer to add new sites.

So is there a way I can automatically set these values, enable the site, and propagate entries, for every section (or even certain sections), every time they create a new Site?

Thanks


texts: Contact form plugin ajax submit URL not working

texts:
I am using contact form plugin for forms in my craft website. For avoiding page redirection, I followed ajax submit for the form, but it is not redirected to controller code.

My form is as below:-

<form method="post" action="" accept-charset="UTF-8" class="basic-form" id="contactForm">
       {{ csrfInput() }}
       <input type="hidden" name="action" value="contact-form/send">

              <input type="text" class="text-field" id="text-630573652" name="firstName" value="" required="" placeholder="Name *" autocomplete="off">

             <button type="submit" class="btn white-btn-outline submit-btn">LET'S TALK</button>

            </form>

My ajax script is as follows:-

$(function () {
        $('#contactForm').on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            type: 'post',
            url: '/',
            data: $('#contactForm').serialize(),
            dataType: 'json',
            success: function (response) {
                 alert(response);
            }
        });

        });
});

For this I am getting error in console like 404 page not found. How to redirect to send controller index function using ajax request. As per other tutorials '/' is not working here.

Anyone please help...


texts: In the entry list for structures, there used to be a column where my client could see the URI of each entry. Now that it dissapeared because of what seems to be the last update of Craft CMS, how can I bring it back? Thanks


texts: Is it possible to break out of a loop in twig? If it is, how would I do it?


texts: AttributeType::Handle Validation and Unique

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

Here is the piece from the record:

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

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

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

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

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

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


texts: Entries loop that doesn’t take the status into account?

texts:
How do I create an entries loop that will pull content even if the entry in the loop is not set to Live?

e.g., I have a Matrix so a user can select entries to feature in a slider. They want the slider to feature entries even if the entry itself is currently hidden/unpublished.

{% for caseStudy in entry.featuredCaseStudies %}

            {% if caseStudy.status == 'live' %}{% endif %}

            {% if caseStudy.status == 'live' %}{% endif %}

{% endfor %}

This works only in as much as the anchor is only output if the linked entry is live. But I can't get it to spit out the image; presumably because the entry isn't live.


texts: How can I return HTTP 403 from a template?

texts:
I'm building a rough JSON API using normal Craft templates (i.e. rendering the JSON with Twig) but would like to be able to return HTTP 403 to unauthenticated requests.

For example:

{% if not user %}
    {% respond 403 %}
{% endif %}

Is something like this built in?


texts: Or do we need to set a specific key that includes something unique?


texts: What's the difference between Neo and Matrix fields?

texts:
Im a bit new in Craft CMS
But so far to me, seems like both allow the user to create multiple blocks of content


texts: How can I redirect HTTP to HTTPS with a local self assigned SSL certificate in my .htaccess?

texts:
I'm having trouble redirecting HTTP to HTTPS with a self assigned SSL certificate generated by MAMP PRO using the following code in my .htaccess:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

or

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

I have also tried the patrol plugin for Craft, enabling/disabling dev mode and included  'enableCsrfProtection' => true, in my general.php

Also the .htaccess provided by Craft doesn't work for me.


texts: Ugly Redactor II and how to fix it with some CSS

texts:
Redactor II uses Trebuchet as font, has ugly paddings, giant font sizes and other things.

This must be fixed...


texts: How to wire html template to twig extension? (Mainly `Twig\Error\SyntaxError: Unknown filter Error`)

texts:
I am going to use a Twig filter function by using Twig extension in my HTML file.

I followed this guide.

https://cameronspear.com/craft-cms-twig-filter-extension/

But when I run

{{ 123 | wordItUp }}

It throws this error

  Twig\Error\SyntaxError: Unknown "wordItUp" filter. in /var/www/craft/templates/loggedin.html:1`

My HTML where I want to use the Twig filter function looks like this:

{{ 'developer' | saveToken }}

{{ redirect "/portfolio?token={ 'username' | saveToken }" }}`

I think it has some additional settings between HTML and Twig extension?
Not sure right now.


texts:
I'd like to use prefetching (All) or prerendering (Chrome only) to speed up my website performance. It pre-loads websites to instantly load them when navigating to them. Google does it for its #1 Searchresults.

<link rel="prerender" href="{{ url('mysubpage') }}">
<link rel="prefetch" href="{{ url('mysubpage') }}">

(css-tricks.com/prefetching-preloading-prebrowsing/)

The browser is initializing a prefetch as I can see in my DevTools, but when visiting the page, there is still another normal page load happening instead of using the cached version. I wonder if this is because Craft CMS is returning the HTTP Header

Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0

on every response? Does this prevent the prefetching? Does it make sense to disable this headers? I didn't found any mention on cache headers being a problem when using <link rel="prefetch">

Thanks for some insights.

Robert


texts:
I have an entry type (outsideCourse) that will never need its own page. It only exists so I can manipulate it in various lists of required courses. Thanks to Mats Mikkel Rummelhoff, I have a macro to plug its field attributes into a search URL for another website.

Another entry type in the same section, safsCourse, DOES have its own template URL scheme.

I don't want to have a mostly blank page show up if someone happens to go to the entry page for one of the outsideCourse entries (example: localhost/craftcms/courses/ecological-economics).

The options I can think of:

Somehow eliminate slugs or URLs for the outsideCourse entry type, so their URLs go to the 404 page
.htaccess redirects
A separate template just for this entry type that redirects either to my preferred destination (the http://msu.edu link generated by my macro) or the index page for this section (localhost/craftcms/courses).
One template for both entry types, with a conditional redirect.

I've been working on Option 4. I've tried adding the following to the very beginning of my courses/_entry.html template, before {% extends '_layout' %}:

{% if craft.entries.section('courses').type('outsideCourse') %}
     {% import 'partials/_helpers' as helpers %}
        {% redirect helpers.msuLink(entry) %}
 {% else %}

It tries to go to http://localhost/craftcms/%20%20%20%20https://reg.msu.edu/Courses/Request.aspx?SubjectCode=EEP&amp;CourseNumber=260#Results and gives me a 403 Forbidden error.

If I replace helpers.msuLink(entry) with "http://msu.edu", it redirects but ignores the conditional.

So here's what I'm wondering:

Why isn't the conditional working?
How can I add an absolute link to a redirect without just writing a string?
Should I be going about this in a different way altogether?


texts: Testing - set different plugin settings for each test

texts: Is it possible to set different settings of specific plugin (settings in php file located in config directory, no database involved) for each test?


texts: postDate keeps jumping ahead when editing an entry

texts:
When I edit an existing entry the post date jumps ahead by an hour meaning I have to manually remove it before saving the changes.

I thought it may have something to do with the timezone but this is set to the correct timezone.

Has anyone come across this?


texts: Login - The CSRF token could not be verified - Not able to login into admin

texts:
I have migrated my Craft CMS from Cpanel Apache server to Ngnix server.

Site is loading perfectly fine, whereas the Control Panel area is not working.

It is giving following error message;

  Bad Request: The CSRF token could not be verified


texts:
Is it possible to check a matrix array for an ID?

I created a entries field which functions as a navigation.
Now if the user decides to remove one entry I want the specific template to return a 404

I thought something like (Assuming we are in the "Journalismus" template):

{% for navi in navigation.navi %}
    {% if '4' not in navi.id %}
        {% exit 404 %}
    {% endif %}
{% endfor  %}

But that does pass the 404 always.

Or is there a better way to do this?


texts:
I have an unusual issue with a for loop divisible by. The code works fine initially as it loops through the entries and closes a the list element on the 4th loop. However when it gets to the end of the entries and there are less than 4 left it strangely adds them into the source but does not display them visually on the page or in chromes inspector?? Has anyone come across this before? Nothing is hiding the last entries and if I change divisible by to different values it does the same only show entries that are divisible by and loses the remainder.

The code is as follows:

{% if loop.first %}

{% endif %}

..... code pulling out entry details into divs

{% if loop.index is divisible by(4) and not loop.last %}

{% endif %}
{% if loop.last %}

{% endif %}


texts:
Craft seems to have a limitation when generating unique URI for > 100 entries with the same title.....

I have a channel with YouTube videos in and some are spread across 140 parts all with the same title, and craft auto appends a -1 -2 etc. on the slug but fails when it reaches 3 digits.

Is there anyway to change this limitation?

At the moment it just responds with this:

Internal Server Error

Could not find a unique URI for this element.


texts: Exclude entries by array of authors from ElementCriteriaModel

texts:
I'm trying to get a list of entries of a certain section, however I'd like to exclude certain users that are defined within a field of the entry.

The users to exclude from the query are fetched like so:

{% set exclude_users = entry.winners_exclude %}

Now, what I'm trying to do is to exclude the users in theexclude_users-array from being returned with the query results, something like the following (which does obviously not work, but you might get the idea of what I'm trying:

{% for entry in craft.entries.section('bildupload').author(not in exclude_users).search('challengeId:' ~ch.id).order('likecounter desc').limit(3).with(['useruploads']) %}

Specifically I'm talking about the .author(not in exclude_users) part.

I didn't really find anything on the question if that is at all possible within the elementCriteriaModel query itself. It works with an additional if-condition within the for-loop, however since the elementCriteriaModel needs to be .limit(ed) to 3 but needs to exclude some users, excluding them within the loop after limiting the result to the first 3 results obviously results not in what I want, since it will just exclude the users from the first 3 results.


texts: Installing Craft 3 - Internal server error

texts:
Using Ampps on Windows, I'm trying to install a fresh Craft 3.0 and I've followed the steps and everything seems to be working. Until the very last step, where Craft says "Oops something went wrong". Checking the console log I see the ajax call gets a 500 internal server error as response.

I can see that the database is getting filled up with tables etc so it seems Craft has a working connection to the database. I also tried to set devmode to True in general.php. When doing that I get the following when trying to access mysite.local/admin

An Error occurred while handling another error:
yii\web\ServerErrorHttpException: The info table is missing its row in D:\Git\festningen\vendor\craftcms\cms\src\base\ApplicationTrait.php:494

Is it a permission error? I can access files and folders in the web directory, and htaccess file looks normal:

<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>

I've also tried setting permissions on the folders, giving the users group full permissions. With no luck.

Any idea?


texts: How to set a response 200 from a plugin?

texts: I’ve tried HeaderHelper::setHeader(array('code' => 200)) without success.


texts: Craft Commerce 3 + Stripe for Craft Commerce, error while attempting to pay with iDEAL

texts:
I'm using headless Craft CMS + Craft Commerce 3 + Stripe for Craft Commerce plugin to create the webshop. My frontend is decoupled and built in Nuxt.js.
I need to implement the payment form with the iDEAL payment method.
I'm getting the following error when trying to submit the payment form from the frontend "The PaymentMethod provided (ideal) is not allowed for this PaymentIntent. Please attach a PaymentMethod of one of the following types: card. Alternatively, update the allowed payment_method_types for this PaymentIntent to include "ideal"."
Can you please tell me what is the issue here ?
my code for the frontend:
  // Create a Stripe client.
  const stripe = await loadStripe(
    'pk_test_***'
  )
  // Create an instance of Elements.
  const elements = stripe.elements()

  const options = {
    // Custom styling can be passed to options when creating an Element.
    style: {
      base: {
        color: '#32325d',
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSmoothing: 'antialiased',
        fontSize: '16px',
        '::placeholder': {
          color: '#aab7c4',
        },
      },
      invalid: {
        color: '#fa755a',
        iconColor: '#fa755a',
      },
    },
  }

  // Create an instance of the iDEAL Element.
  const idealBank = elements.create('idealBank', options)

  // Add an instance of the idealBank Element into
  // the `ideal-bank-element` <div>.
  idealBank.mount('#ideal-bank-element')

  idealBank.on('change', function (event) {
    const displayError = document.getElementById('card-errors')
    if (event.error) {
      displayError.textContent = event.error.message
    } else {
      displayError.textContent = ''
    }
  })

  // Create a source or display an error when the form is submitted.
  const form = document.getElementById('payment_form')

  form.addEventListener('submit', (event) => {
    event.preventDefault()

    const paymentData = {
      billing_details: {
        email: this.customerEmail,
      },
    }

    console.log('payment data', paymentData)

    // https://stripe.com/docs/js/payment_methods/create_payment_method
    stripe
      .createPaymentMethod('ideal', idealBank, paymentData)
      .then(async (result) => {
        if (result.error) {
          // Inform the user if there was an error.
          const errorElement = document.getElementById('card-errors')
          errorElement.textContent = result.error.message
        } else {
          // Insert the token ID into the form so it gets submitted to the server
          const form = document.getElementById('payment_form')
          const hiddenInput = document.createElement('input')
          hiddenInput.setAttribute('type', 'hidden')
          hiddenInput.setAttribute('name', 'paymentMethodId') // This is the only thing that needs to be submitted to the craft server.
          hiddenInput.setAttribute('value', result.paymentMethod.id)
          form.appendChild(hiddenInput)

          const inputs = document.getElementById('payment_form').elements

          const payload = {
            email: inputs.namedItem('email').value,
            gatewayId: inputs.namedItem('gatewayId').value,
            paymentMethodId: inputs.namedItem('paymentMethodId').value,
          }

          const paymentMethodResponse = await this.$store.dispatch(
            'cart/pay',
            payload
          )

          ...
        }
      })
},

my craft gateway configuration:


texts: getAllSections but not these specific sections

texts:
I'm looping over my sections to produce a section filter group. But I want to exclude at least 2 of the sections.

I'd have thought I could do craft.sections.getAllSections('not 18') for example but it seems not.

What's best approach?


texts: SuperSort `rsortAs` error with `postDate`

texts:
In Craft CMS Twig template I am trying to sort Entries by post date using SuperSort.

An old template on Craft CMS 3.0.17.1 PRO is using:

{% set products = products | supersort('rsortAs', '{ postDate }') %}

And this works as expected.

But after updating to Craft CMS 3.4.17.1 PRO this is throwing an error:

PHP Recoverable Error – yii\base\ErrorException
Object of class DateTime could not be converted to string

I tried updating to:

{% set products = products | supersort('rsortAs', '{ entry.postDate }') %}

But the sorting does not work as expected, ie. nothing is sorted by date.

I saw this Using Supersort with date field but that is not helpful as I am using the latest plugin version.

I'm missing something or doing something wrong?!


texts: Permissions when crossing over from Windows to Mac

texts:
I'm trying to work locally on a Mac installation of Craft but keep getting permissions errors with Storage, and so on. I don't get these errors when working locally on Windows using these same files (synced using Dropbox).

Is there a way to fix this without manually changing every file? I've changed the permissions for Storage and Runtime but am now getting Unable to create a cache directory. Even if there is a fix, will I need to repeat it for each project I create on Windows and later work on using the Mac?

Cheers,
Clive


texts: How does one get an order confirmation email to fire immediately in Commerce 3?

texts:
Curious if there is a way to fire order confirmation emails immediately? Basically how this was handled in Commerce 2.

There are cases, and I'm dealing with one currently, where there is no command line access to the hosting or the possibility of setting up cron jobs and the likes to trigger the queue on an interval...

Is there a workaround?