texts: How to get an entry title and URI from a segment in order to create a breadcrumb navigation

texts:
Is it possible to get an entry title and URI from a segment? e.g. If segment 1 has a value of 'about', I'd want to output an entry title of 'About Us', and a URI of 'mysite.com/about', and so on for other segments.

I'm trying to code up a breadcrumb menu, and my site has a mixture of Singles, Structures and Channels.

I have the following _includes/nav_breadcrumb.html template, but I'm hard-coding everything at the moment (and only have it one level deep) so it's not going to be sustainable to keep this up-to-date on anything but the smallest of static sites, hence why I'm wondering about being able to pull in entry details via the segments. Thanks for any help with this.

Home &raquo;

{% if craft.request.getSegment(1) == 'about' %}
  About

{% elseif craft.request.getSegment(1) == 'news' %}
  News

{% elseif craft.request.getSegment(1) == 'contact' %}
  Contact

{% endif %}


texts: Access-rights at lower granularity than section?

texts:
I would like to make a page where different groups of users would only have access to the entries created by their own group.

Now I can create a group and give it access to a certain section, but ideally I would like all groups to edit the same section, but different entries.

There is a "edit other people's entries" permission, but not on the group level.

Never satisfied, I would ALSO like to be able to limit visibility of the entries a user cannot edit, not just whether they can be edited/deleted?

There isn't a "can user view this" hook is there? Or a "visible by X,Y,Z" flag on posts I could set?

Thanks!


texts: Calling template from controller redirects to dashboard

texts:
How can I call a template with variable from a controller method? I tried following but it redirects to dashboard:

public function actionsetDate() {
        return craft()->templates->render('index');
    }


texts: Upgrade to 3.0.0 RC1 failed due to 504 Gateway Time-out

texts:
I got a notification in the Craft 3 beta versions I have been working on to upgrade to 3.0.0 RC1. I clicked update and it began updating only the throw the following error. Any ideas what may have happened?

Status: Gateway Time-out

Response:
<title>504 Gateway Time-out</title>

504 Gateway Time-out

nginx/1.12.2

If it's of any help, this is a composer install using Valet to run.


texts: Is it bad practice to re-use array variable name?

texts:
I have this line

{% set entries = craft.entries.section('x') etc etc %}

Which I use to pull data for a header in my _layout.html template.

Then later, knowing I am done with the array, inside a block in an another template which extends _layout I have

{% set entries = craft.entries.section('y') etc etc %}

In fact I have reused the 'entries' name regularly through many templates and a number of sites and haven't, as far as I know, had a problem, except in one case.

In this case if the cache has just been cleared (manually at least) then the second setting of entries does not work and it contains the values from the first set, mucking up the page of course.

On reloading the page, and subsequently until the cache is cleared manually every thing works as expected (although I don't know what happens when the cache automatically clears as I am never sure when that has just happened).

It was an easy fix just to change 'entries' to 'whatevers' in the second line, and where it is referred to in the rest of the template.

Is it bad practice to do what I have done (before the change), or is it likely that there is another error in my code that is causing this problem?


texts: How do I group matrix blocks into batches of 4?

texts:
I am building a site which uses one content type as its primary holder for content. This is to make content editing easier on the content editor.

All URL's are primarily accessing this one content type, 'events'.

Within 'events' I have a matrix field 'authors'. Authors contains 1 block (also 'authors') with 4 fields, Name, Image, Bio and URL.

I am able to output the matrix blocks fine, but I am not familiar with a way to call all event entries without running them through a for loop first. Doing so causes my row/col layout to break but without batching them into groups of 4, my column layout also breaks.

I have attempted all solutions shown on stackexchange but none of them are suited for this scenario (calling all entries from a section) and my attempts at rewriting it to fit my solution has failed. Any help would be greatly appreciated.

{% for event in events %} {# loop through all events #}
    {% if event.startDate|date('Y') == now|date('Y') %} {#check to see if the event's start date is happening this year #}
        {% for row in event.authors|batch(4) %} {# use batch to create rows #}

                {% for block in row %}
                    {% switch block.type %}
                        {% case "author" %}

                                {% set image = block.image.first() %}
                                    {% if image|length %}

                                     {% endif %}

{{ block.authorName }}

                                {% if block.twitterHandle|length %}

@{{ block.twitterHandle }}

                                {% endif %}
                                 {{ event.startDate|date('m/d/y') }} @ {{ event.startDate|date('g:ia') }}

{{ block.bio }}

                    {% endswitch %}
                {% endfor %}

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

This is as close as I've gotten, but unfortunately this just creates rows for each entry as opposed to every 4 blocks.


texts:
I'm looking to fetch all line items and send it as a POST request to an endpoint. I've had a look through the class references but can't seem to find a way to get all the line items that are currently active.
Event::on(
  Payments::class,
  Payments::EVENT_BEFORE_CAPTURE_TRANSACTION,
  function(TransactionEvent $event) {

        $transaction = $event->transaction;
        // @var LineItem $lineItem
        $lineItem = $event->lineItem;

        $client = new \Guzzle\Http\Client([
            // You can set any number of default request options.
            'Authorization'  => 'qdaiciDiyMaTjxMt, 74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875',
        ]);

        // Add Cart Data to an Array
        $order_data = array(
            'product_id' => $lineItem->id,
            'quantity' => $lineItem->quantity
        );
...


texts: Performing Image Transformations Locally

texts: Is there any reason why image transformations might not be working locally? I just get a bunch of these "http://site.dev/cpresources/transforms/7 404 (Not Found)" as error messages. The image directory has the correct permissions...


texts:
I am very new to Craft and how it works. I've got a client with a Craft site (v2.9.2), that I help them with. It was created by another developer.
I want to help them tidy up their Assets.
There are two folders (on S3) for their Assets. /Media and /Media/Files.
Scanning by eye, I can see /Media/Files appears to be a subset of what's in Media (meaning, they are duplicate files). Before we potentially delete the /Media/Files folder, I'd like to programatically confirm if any of them are being used. My suspicion is only files in /Media/ are used on the site.
Is there any easy way to see which assets are in use, and where they are used?
I found questions on StackExchange re how to see what media is not in use, such as this one. I also found a question on how to do something similar to what I need.
Although, to be honest, I had no idea where I'd utilise such code. I'm not going to get into creating a new plug-in.
For example, this was shared in the answer to that question:
{% set content = craft.entries.section('content').find() %}
{% set usedFotos = craft.assets.relatedTo(content).order('filename').find() %}

{# Loop throught the array of assets #}
{% for usedFoto in usedFotos %}

{{ usedFoto.filename }}

        {# Loop throught entries related to this asset #}
        {% for entry in craft.entries.relatedTo(usedFoto).order('title') %}

{{ entry.title }}

        {% endfor %}

{% endfor %}

Where would I utilise this code?


texts: Reference a field name relatedTo(category)

texts:
I'm building a site for a property developer that has multiple housing developments. And on each development page there is a siteplan image that shows a CGI of the all the houses on the development.

I'm trying to implement the Donkeytail plugin https://straightupcraft.com/craft-plugins/donkeytail-lite which lets you add pinpoints on images and have made some progress and have it working. However, every development page needs it's own siteplan, and so I have to create a field for each one.

So my question is how do I reference it in the template dynamically? As currently it is being called via variable.fieldname.topLeftStyles

But this only references the exact fieldname of one siteplan. So I need a dynamic way so that it can be different on each development page.

{% set sitemap = craft.entries.section('sitePlan') %}
{% for variable in sitemap.relatedTo(category) %}
    {{ variable.title }}
{% endfor %}


texts: I am trying to have a vertical tab with hidden content

texts:
In Craft 3, I am trying to build a vertical tab categories using href=#sample and the hidden content id=sample. I am using bootstrap JS as my library. Here is the code I use. I somehow not managed to hide my content, as the method I am using is if and else. Does anyone have any idea? I'm using entry.title for both the href and id. Ignore the onclick, I was trying out something with it.

            {% for entry in entries %}
                {{entry.title}}
            {% endfor %}

            {% for entry in entries %}
                {% set thumb = entry.singleImage.first() %}

{{entry.text}}

                    Click Here

            {% endfor %}

The problem with this method is that instead of showing one tab-content per href, it is showing all.


texts:
I have an Entry Type with a field called Gallery with a handle of gallery. Here are two examples of how I can access the Gallery field in a template:

{% set images = entry.gallery %}

{% set images = craft.assets({
    source:    'images',
    relatedTo: {sourceElement: entry.id, field: 'gallery'},
    order:     'sortOrder'
}) %}

The problem:

The first method works with Live Preview, the second does not. This wouldn't be an issue, but it's my understanding that we have to use the second method to eager load elements. So if I wanted to eager load a relationship on my gallery images, then Live Preview wouldn't work.

Is anyone else running into this issue? Is it a known bug or a misunderstanding of the implementation?

Thanks

Edit

To clarify via Brad's question, the following is the only thing in my template. This does NOT work with Live Preview:

{% set images = craft.assets({
    relatedTo: {sourceElement: entry.id, field: 'gallery'}
}) %}
{% for image in images %}
    {{ image.url }}

{% endfor %}

The entry variable is populated defining the Entry Template in the section settings.

Using the following WORKS with live preview:

{% set images = entry.gallery %}
{% for image in images %}
    {{ image.url }}

{% endfor %}


texts: Ok so I know this is something really basic but unfortunately i could not find it in the documentation and I don't have a lot of experience with localisation at all. i have set up two locales in my craft admin panel and I have also updated general.php, etc to set up content localisation. But unfortunately the content that i set as translatable is still displayed in english at both the en and zh site post-fixes. Can somebody simply explain how can I use a link to change the language of all my content on a page to another language inside of a template?


texts: How to initiate a date picker when template is loaded remotely from controller action

texts:
I have a controller action which returns JSON with a rendered template.  This template uses date picker form fields.  How can the date picker JS be initialized since the html is returned through JSON. I would have thought since the date picker field includes the necessary JS within {%js%} tag during template render it would be initialized. Could it be the timing of render vs adding the template html to the DOM? (Craft 3)

$view = $this->getView();

$html = $view->renderTemplate('_modal',['values' => $values, 'siteId' => $siteId]);
$headHtml = $view->getHeadHtml();

return $this->asJson(['html' => $html, 'headHtml' => $headHtml]);


texts: Rest Controller and API Rate Limits or how to set CSRF token invalid

texts:
Problem:
I have a JSON endpoint and like to limit access to it.
I.e. to prevent double submits on contact forms or brute force attempts.

One solution that came to my mind was rate-limiting the requests, but I did not find a Craft way to archive this with my controllers.

Another idea was to set the CSRF token to invalid after X requests.
Any help would be highly appreciated.


texts:
I have a channel (handle: "infopages") with entries.
I have a channel (handle: "products") with entries.
I have a category (handle: "productTypes")

Every entry from "infopages" has a category field, called "relatedCat". Every entry from "products" has a category field, called "relatedCat".

In the template for the infopages, I want to show all entries from "products" that share the same category. So if an infopage is related to the category "robotmowers", I want to show all the entries from "products" that are also related to "robotmowers". Every entry in every channel can be related to multiple categories, that's where the hard part comes in.

I could loop through the "relatedCat" field and get all the related entries from "products" in a loop. However, if multiple categories are selected, that means I possible get the same product entry more than once. I guess there must be a better way to do this?


texts: How would I list assets from a specific subfolder?

texts:
In the case that I have an asset folder structure like this:

/images
   /group-a
   /group-b
   /group-c

How would I loop through all of the images in /group-b without having to assign them to entries.


texts:
Hey guys I have created a plugin with an accompanying Stylesheet which I am adding to the page via

class SitemaphtmlPlugin extends BasePlugin
{

function init(){

     craft()->templates->includeCssResource('sitemaphtml/css/sitemaphtml.css');
}

however the link being generated is prefixing the path with cpresources/ making it 404.

/cpresources/sitemaphtml/css/sitemaphtml.css?x=xXhFyszUs

how can i overcome this this?

Cheers


texts: How do you pull entries with a specific category value?

texts:
Help, I forgot how to do something basic.

How do I pull all the entries in posts for a specific category value (field name = countryName) within the category group called country?

And I am NOT using the template for posts or the category.

I can pull all the entries using

{% for doc in craft.entries.section('posts') %}
--OR--

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

But, I forgot how to now add a second condition to pull up only those entries with the countryName (say) "United Kingdom"?

Thank you.


texts: How to get core shipping methods in Commerce 2? How to save an order?

texts:
Is there an equivalent function to commerce_shippingMethods->getAllCoreShippingMethods() in Commerce 2?

I can only find Commerce::getInstance()->getShippingMethods()->getAllShippingMethods();

I also cant find an equivalent to craft()->commerce_orders->saveOrder($order) anywhere.


texts:
I have a loop of a list of regions on a project, this could be an infinite list of areas as my client's customer-base grows.

The project branding has four key colours, I have these in an array:

{% set themes = [
    'yellow',
    'red',
    'teal',
    'blue'
] %}

What I'm looking to do is grab one of these themes as I loop over my regions with a basic {% for region in regions %}, then on the 5th, 9th and so on loop jump back to #1.


texts: Is the Craft Queue suitable for processing form submissions?

texts:
I am looking to queue my form submissions to be processed in the background.

I want to be able to only keep user data in the system/database as long as required. This will mean keeping it to debug it if something goes wrong in the processing (SMTP error to send the email, store in database/google sheet, etc)

As a bonus I figure queuing should mean faster success responses to users (rather than waiting for whatever processing is required), and can also throttle the processing if a form gets hit with lots of submissions in a short period (such as a competition).

Looking for clarification if:
1. Using the Craft Job queues is best for this.
2. If should just use the default queue, or better to have a separate queue


texts: Craft CMS plugin action debugging with IntelliJ

texts:
I have xDebug and IntelliJ setup to debug Craft and can run a debug profile where it stops on a breakpoint in index.php and interprets all the variables, etc. in IntelliJ console. However, it never gets to the plugin action when running host/plugin/someaction which has in that action a breakpoint.

Any suggestions?


texts:
I've set up a site to send emails via Mandrill over SMTP.
However, this does not seem to be sending emails.

If I test the email config it says a message has been sent but the email is not received and there is no record of the email in the Mandrill Outbound messages.

Sending over SSL (which has worked on other Craft sites on same host) on port 465.

Suggestions appreciated as client not receiving messages through the site.

Cole


texts: Module Development - Get ID of a field within a Matrix field

texts:
I have a matrix field that has a Supertable matrix within it.

I need to programatically get the ID of the field that is nested in the Matrix.

I have the code below:

$matrixField = Craft::$app->getFields()->getFieldByHandle('myMatrixFieldHandle');

Which gets me my Matrix field element, but I can't figure out how to get the fields that are within that Matrix field and thus the ID of the field within the Matrix field.

Any help appreciated!


texts: Delete Stale Template Caches tasks much larger in Production than Staging

texts:
I've been running into issues where the Delete Stale Template Caches tasks on my Production environment are running up to 20x longer than on my identical Staging environment. The config/environment settings are the same across both (including devMode being disabled on Stage) but they use separate databases. So I imported my Prod database into my Stage environment just to get complete parity across both environments to try and diagnose the problem.

I edited the same entry on Prod/Staging and hit save, both kick off the DSTC task, but I got ~10,000 steps on Production as opposed to ~500 on Staging.

I copied the SQL row on each database and this is what I get:

Stage:

14  14  1   2   0   263 555 running DeleteStaleTemplateCaches   NULL    {"elementId":["3282","3342","3343","3341","3548","3549","3550","3547","3382","3383","3381","9171","9172","3395","3391","14629","14630","14628","3281"]} 2016-07-14 18:38:46 2016-07-14 18:38:52 d39e2b0f-e6d6-446d-9d2b-30d35ecca378

Production:

16042   16042   1   2   0   439 9864    running DeleteStaleTemplateCaches   NULL    {"elementId":["3282","3342","3343","3341","3548","3549","3550","3547","3382","3383","3381","9171","9172","3395","3391","14629","14630","14628","3281"]} 2016-07-14 18:36:46 2016-07-14 18:37:07 b152c337-2316-45c9-8b29-4716faf41897

The settings of the tasks are the exact same as far as the ElementIds that it involves, but the Stage task is 555 steps while the Production task is 9864. I'm seeing this pretty consistently across all entries - the number of steps in the Production environment is around 20x the Staging on identical entries.

I'm a bit stumped as to why this is happening -- what determines the number of steps involved in any given DSTC task?

EDIT: Another odd thing is that it's kicking off the tasks on entries that don't have any cache tags inside the templates. Again this is only happening in Production, it seems that the Staging site seems to recognize that these templates shouldn't be getting cached in the first place.


texts:
I am developing a website on Craft CMS and now I need to change the domain for my Craft account. Because it's giving me an error "The license located at config/license.key belongs to...."

I do not have any details about the Craft ID all I have is the license key.

Is it possible to recover my Craft credentials using my Craft license key.


texts: What's the best way to setup a conditional to see if a matrix block is used?

texts: I need to add some javascript to a page depending upon whether or not a matrix block is used, one is for a slideshow block to load responsiveslides.js, another is for a video block to load fitvid.js. If I place it in the loop then I will get the javascript repeated for each time an entry uses that matrix block. I'm looking to add this towards the bottom of the template and load the .js files once each if the block is used in a loop above. What's the best way to do this?


texts:
I have multiple checkboxs in a form

<input type="checkbox" name="Classification[]" value="Hub Zone">Hub Zone
<input type="checkbox" name="Classification[]" value="Not Applicable">Not

After submit Get info is:

 'Classification' =>
  array (
    0 => 'Hub',
    1 => 'Not Applicable',
  ),

and I get error : array to string conversion on below code

 'Classification'  => array(AttributeType::Mixed, 'required' => true, 'label' => 'Classification')

stack Trace:

PHP notice
Array to string conversion

/home/www/html/www3/craft/storage/runtime/compiled_templates/3d/3df3f71b6051f05e907988ee087f2136f9ad04870a88d4a66539df50db139f6d.php(39)

27         }
28         // line 6
29         if ((array_key_exists("fields", $context) && twig_length_filter($this->env, (isset($context["fields"]) ? $context["fields"] : $this->getContext($context, "fields"))))) {
30             // line 7
31             echo "    ";
32             $context['_parent'] = $context;
33             $context['_seq'] = twig_ensure_traversable((isset($context["fields"]) ? $context["fields"] : $this->getContext($context, "fields")));
34             foreach ($context['_seq'] as $context["_key"] => $context["field"]) {
35                 // line 8
36                 echo "        ";
37                 echo twig_escape_filter($this->env, $this->getAttribute($context["field"], "label", array()), "html", null, true);
38                 echo ": ";
39                 echo twig_escape_filter($this->env, $this->getAttribute($context["field"], "value", array()), "html", null, true);
40                 echo "
41
42     ";
43             }
44             $_parent = $context['_parent'];
45             unset($context['_seq'], $context['_iterated'], $context['_key'], $context['field'], $context['_parent'], $context['loop']);
46             $context = array_intersect_key($context, $_parent) + $_parent;
47         }
48         // line 12
49         if ((array_key_exists("footer", $context) && twig_length_filter($this->env, (isset($context["footer"]) ? $context["footer"] : $this->getContext($context, "footer"))))) {
50             // line 13
51             echo "


texts: The requested URL was not found on this server. Apache/2.4.18 (Ubuntu) Server at localhost Port 80

texts:
The frontend just work fine. But when I call the backend http://localhost/craft3/web/admin/dashboard/ or http://localhost/craft3/web/admin/ I get the error
requested URL was not found on this server.
Apache/2.4.18 (Ubuntu) Server at localhost Port 80.
The admin-folder doesn't exist in web-folder.
I searched here for this problem, but they had problem with frontend.


texts:
I need to use a Typekit font in Redactor, but I'm not quite sure if I've done something wrong, or if Redactor's made a breaking change.

I'm enabling the iframe = true parameter in a custom.json redactor config, and then loading Typekit with the initCallback parameter. However, Redactor isn't placing the iframe (as of Craft Pro 2.4.2691) that Typekit uses for selection purposes.

Any ideas? has Redactor recently made a breaking change?

TL;DR: What's the best-practice for using Typekit fonts in Redactor fields as of Craft Pro 2.4.2691?


texts: Checking submission from the Contact Form plugin

texts: I've potentially have had some messages not come through to email. I've seen the user has reached my thank you page but I don't always receive a message. Are these stored anywhere in the Database to check?


texts:
I have a comment section with comments and subcomments. A comment relates directly to the blog post while a subcomment relates to a comment.

Now, I have the following problem on the entry page: Showing the comments only is not a problem:

{% for comment in craft.entries({
    section: comments,
    relatedTo: { targetElement: entry, field: "relentry" },
    order:     "sortOrder",
    limit:     null
}) %}

X

{% endfor %}

But when I insert the subcomments, I get the error message Unexpected "}":

{% for comment in craft.entries({
    section: comments,
    relatedTo: { targetElement: entry, field: "relentry" },
    order:     "sortOrder",
    limit:     null
}) %}

X

    {% for subcomment in craft.entries({
        section: comments,
        relatedTo: { targetElement: comment, field: "relentry" },
        order:     "sortOrder",
        limit:     null
    }) %}

Y

    {% endfor % }
{% endfor %}

Thank you very much for your help!


texts: Displaying the optional note from a versioned entry

texts:
I want to use the note that is optional when saving a versioned entry as part of an activity feed -- like a git commit message.

Is there an entry model property for this?


texts:
I'd like to be able to attach custom JS to a Sprout Form which can be managed in the form builder. I need to add logic that will switch the email address of the recipient based on a choice from a select menu. For example, "Website Issues" goes to "websupport@mywebsite.com", and "Information" goes to "info@mywebsite.com".

Ideally this JS would be managed at the form builder level so it only loads for that specific form.

I'm in the testing phase of Sprout Forms, so I apologize if I'm missing something obvious.


texts: Why is my base installation of Craft 3 so slow on Azure App Services?

texts:
I am evaluating a few different CMS solutions for my company's new website. Everything about Craft looks great according to my research. After installing version 3 onto an Azure App Service Linux instance I'm growing concerned about the viability, though, due to poor performance. The control panel is taking at least 4 seconds TTFB regularly. The "Welcome Thanks for installing Craft CMS!" default page is taking about 3 seconds TTFB consistently.
I've ensured I followed the installation and setup steps properly. I've ruled out a network issue. I've run the installation in an App Service plan that far exceeds what should be required for even moderate performance. After running the (very awesome) diagnostic tool it seems that the twig rendering is mostly to blame, although my DB queries aren't running as quickly as I would hope. That might just be due to an undersized MySQL instance on Azure. I can deal with that if I get the more blatant twig issues resolved.
I've run non-Craft php web pages from the instance and they return very quickly, sub 100ms. So I don't think the php or webserver installation that Azure provides is fundamentally bad. I'm banging my head against the wall at this point. Can someone shed any light on next steps? I really want Craft to be an option for our new platform, but I can't sell it to the stakeholders unless I can make it significantly more performant.
Thanks for any help you can offer.
Please see the performance results below.
Application Info

PHP version  7.4.9
OS version   Linux 5.4.0-1031-azure
Database driver & version    MySQL 5.6.47.0
Image driver & version   Imagick 3.4.4 (ImageMagick 6.9.10-23)
Craft edition & version  Craft Pro 3.6.4.1
Yii version  2.0.40
Twig version v2.14.3
Guzzle version   7.2.0


texts: Folders required to download when moving a Craft 3 installation to another server?

texts:
If I'm downloading a Craft 3 website one server in readiness to deploy onto a new server, which folders should I download aside from?:

/templates
/web

Also, do I need to redownload the 'cpresources' folder again inside the /web directory if I already have a local copy of Craft CMS installed?


texts: Getting this SQL Error: GROUP BY incompatible with sql_mode=only_full_group_by

texts:
I am getting the following error:

  Internal Server Error CDbCommand failed to execute the SQL statement:
  SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #18
  of SELECT list is not in GROUP BY clause and contains nonaggregated
  column 'creighton_mma_craft.structureelements.root' which is not
  functionally dependent on columns in GROUP BY clause; this is
  incompatible with sql_mode=only_full_group_by

I have mysql 5.7.9 installed. Logging into the Control Panel is working fine, but the front end displays this message.

During the installation, the screen was stuck at the very end with "Ooops…" message.

I am new to terminal commands and mysql configurations so the more specific the better.

Thanks.


texts: Add field to /settings/sites/new (multi-site)

texts:
I would like to add some fields to the site creation on the control panel settings. I know you can add globals for each site, but I think it would be a better process if I could add additional fields.

For example, I'd like to add a select for whether a site (location) is a franchise or corporate.

Is this possible?


texts: How does one achieve drop-left or drop-right image position?

texts:
How is one to achieve the layout visualised by Craft's drop-left and drop-right icons?

I feel dumb asking but I don't know of any way to have a floated image stick to the bottom of its sibling text node with text running around it above and to the side, which is what is implied by the icons.

What have I been missing all these years?!


texts:
I'm trying to add a "convenience" link from within a plugin to it's general settings page. In the General Settings custom cpTriggers and baseCpUrl can be set to custom values and I'm wondering if there is a easy Craft variable to retrieve a link to the site's correct settings page. It would create something like this in a template.

http://mysite.com/customadminword/settings/plugins/mypluginname

Any thoughts? I could write some logic in the plugin to dig it out but it seems like I might be overlooking something obvious. Any thoughts?


texts: Show shipping rate on Cart screen in Craft Commerce

texts: How can I show the shipping rate on the cart screen? At the moment this defaults to 0.00 - I assume as we don;t know the customers location so no shipping method can be applied. Ideally I want to show the standard shipping rate based on UK and then allow the user to click and change location to apply a different shipping rate. Ideally I want to do this in the Cart screen so users can see the full total before logging in or checkout out as a guest. I want to eliminate the shipping selection page. Any ideas on how to go about this?


texts:
I am using a Controller to get Variables from a field in my Plugin.
How and what would be the best way to pass and use them in other classes or my main plugin file.

I thought about using Sessions or passing them via URL Parameters, but i am not sure if thats the most convenient way.

Thats my controller:

use craft\web\Controller;

class SetUserController extends Controller {
    public function actionSubmitUser() {

        $request = \Craft::$app->getRequest();

        $dateTime = $request->getParam('dateTime');
        $user = $request->getRequiredParam('user');

    }
}

e.g. in my main plugin file i would like to pass the variable to a function:

// check if commerce record for craft user exists
public function checkCommerceRecord($user) {
    return $this->customers->getCustomerByUserId($user);
}

Update:

I figured that i need to setup a module, however i cant save the variables into the module, getting Setting unknown property: wewereyoung\wfwplugin\models\WFWPluginModel::userId

Module:

namespace wewereyoung\wfwplugin\models;

use craft\base\Model;
use craft\validators\ArrayValidator;

class WFWPluginModel extends Model {

    public $setUser = [
        'userId',
        'timeDate'
    ];

    public function rules() {
        return [
            [
                [
                    'setUser'
                ],
                ArrayValidator::class
            ]
        ];
    }
}

Updated Controller:

namespace wewereyoung\wfwplugin\controllers;

use craft\web\Controller;
use wewereyoung\wfwplugin\models\WFWPluginModel;

class SetUserController extends Controller {
    public function actionSubmitUser() {

        $request = \Craft::$app->getRequest();

        $dateTime = $request->getParam( 'dateTime' );
        $userId   = $request->getParam( 'user' );

        $setUser            = new WFWPluginModel();
        $setUser->userId   = $userId;
        $setUser->dateTime = $dateTime;

    }
}


texts: No redirect to 503 from the homepage when system is off

texts:
When isSystemOn => false in the general config; and the user is not logged in. Going to the homepage does not redirect users to the 503 template (holding page). All other pages redirect as expected.

Is this normal behaviour or a bug?

I'm using Craft CMS 3.0.3.1


texts:
Im curious to hear more about what any of you are using to build "community"/ "forum" messaging options into your craft cms site.

From what I've found it seems there would be a couple of interesting options

Socialize Plugin https://dukt.net/craft/socialize

Its in private beta and I haven't tried it but it seems to have a lot of the features we would need.

The big option questions would be how to manage any group messaging features but maybe you just have a "posts" channel that users can post to?

Muut https://muut.com/

Allows for an iframe type integration. Seems to be pretty full featured but wouldnt really share any data (or logins) with craft, would be a visual integration only

Any other options

We aren't looking for a ton of features, just a way for people to login, share text and photos, and comment on those posts.

Curious if anyone out there has tackled a problem like this?


texts: Plugin routing casing: camel, lower, Pascal

texts:
Recently got tripped up with plugin routing due to casing.

It seems when you're in the control panel, your "plugin handle" is lower-cased in routes, though both seem to work: /cp/settings/plugins/myplugin (/cp/settings/plugins/myPlugin` also works)

However, when using an controller action, it seems like it must be camel cased (/actions/myPlugin/foo).

Seems inconsistent, unless I'm missing some reasoning.

The docs say [PluginHandle]/[ControllerName]/[ActionName], but it seems like it's actually [pluginHandle]/[controllerName]/[actionName] as the example shows (cocktailRecipes/ingredients/saveIngredient).


texts: Adding a new block type to Matrix causes subfields and subfields of other block types to disappear

texts:
When saving a newly added block type with subfields to an existing Matrix, the subfields of the new block type are gone and also are the subfields of 6 of the last block types. The whole Matrix contains 29 block types.

I'm using Craft CMS 2.6.2982.


texts: Checking if matrix lightswitch is true, and add wrapper div

texts:
I'm using Zurb foundation's Block Grid and using this in a matrix field where users can (using a block called 'wrapper') add a row and define the number of columns which appear side by side across a desktop device in that row, then using another block 'textBlocks' add divs of text within the row. I also want to add an option of 'fullwidth' a lightswitch field in the 'wrapper' block, so if this is selected then the 'following' will wrap around the row:

…row/text content

but I can't seem to add the closing  in the right place (at the end of the row), code below:

{% set isWrapperOpen = false %}
{% for block in entry.pagedesigner %}

  {% switch block.type %}

    {% case "wrapper" %}

      {% if block['fullwidth'] is defined %}
{% endif %}
      {% if isWrapperOpen %}
{% endif %}

      {% set isWrapperOpen = true %}
      {{ block.heading }}

    {% case "textBlocks" %}

          {{ block.text }}

  {% endswitch %}

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

{% endfor %}

pic added of Publish page

Appreciate semantics need some work but need to figure logic first

UPDATE I've since chatted with Andrew Fairlie from Mutual and got this working (with his guidance) excuse the crude inline styles – just helps aid making visual sense to me :)

{% set isWrapperOpen = false %}
{% set isFullWrapperWidthOpen = false %}
{% for block in entry.pageDesigner %}

{% switch block.type %}

{% case "wrapper" %}
 {# Close the previous fullwidth wrapper before we open a new one #}
  {% if isFullWrapperWidthOpen %}
{% endif %}
  {# Close the previous wrapper before we open a new one #}
  {% if isWrapperOpen %}
{% endif %}

  {% if block.fullWidth %}
    {% set isFullWrapperWidthOpen = true %}

     {% else %}
       {% set isFullWrapperWidthOpen = false %}
    {% endif %}

  {% set isWrapperOpen = true %}

  {% case "heading" %}

    {{ block.text }}

  {% case "textBlocks" %}

      {{ block.text }}

{% endswitch %}

{# If we're on the last block, close up the last wrapper div #}
  {% if loop.last and isWrapperOpen %}{% endif %}
  {% if loop.last and isFullWrapperWidthOpen %}**{% endif %}
{% endfor %}


texts: How to programmatically set a Smart Map address field in plugin

texts:
I have a console command plugin that needs to periodically go and fetch property data via API and import it into Craft. I can pull in basic property information but when it comes to importing the data into Smart Map field I'm a bit lost as how to format the data so that it saves correctly. Has anyone had to do this before?

Edit:

I don't think the console command part should make much difference. Basically I am trying to save a smartmapfield on my entry. From the API I am using I get a string with the full address. I first extract the postcode and then use the smartmap plugin to get the Lat and Lng values:

$postcode = $matches[0];

//Look up Latitude and Longitude from Google API

$response = craft()->smartMap->lookupCoords($postcode);
$lat = $response['lat'];
$lng = $response['lng'];

What I am not sure of is how to format this data so that it can be saved to the entry. So for standard fields thats straight forward:

$entry->getContent()->title = $property['RoomName'];

How do I do this for my smartmap field?


texts: Sprout SEO: How to access meta fields assigned to globals?

texts:
In the Sprout SEO docs you can pass for entries:

{% do craft.sproutSeo.meta({
    id: entry.id
})

And it is smart enough to grab the data. How would could I do similar for meta fields assigned to a global set?


texts: Route token that includes forward slashes

texts:
I'm setting up a route in control panel. I'd like to use a token that is similar to asterisk but involves forward slashes. Here's an example:

I want to route everything from site.com/blog/* to a single template.
If I route site.com/blog/some-uri-identifier , it works fine and I'm able to get "some-uri-identifier" in my template (using slug option).
I need to route site.com/blog/some/uri/identifier-long-name and still go to the same template + get "/some/uri/identifier-long-name" in it.

Thanks!


texts: Formatting postDate using the ElementAPI plugin

texts:
Building a small AngularJS app and using the ElementAPI plugin for the first time.

I can set 'postDate' => $entry->postDate which gives me

postDate : {
   date: "2015-12-10 07:04:02.000000",
   timezone_type: 3,
   timezone: "UTC"
}

as an example.

Now I can access this date in Angular by doing {{note.postDate.date}} but obviously it's just a string so I can't use any native Angular filters for formatting.

Is there a way I can access the postDate with a date format? What options do I have?


texts: Display only entries relevant to users' country

texts:
I'm really struggling with displaying news entry that are only relevant to the users' location.

Here is my structure:

User

Country - > is a dropdown with a single value (lets say UK)

Regions is a category that contains

name -> string (for example Europe)

countries -> a checkbox with a list of countries (UK, FR.. etc)

News which has a Region category

So what I have now is this:

{% for entry in craft.entries.section('news') %}
{# loop through regions  #}
    {% for region in entry.regions %}
        {# loop region's countries  #}
        {% for targetCountry in region.countries %}
            {% if targetCountry == currentUser.country %}
                {% set visibility = true %}
            {% endif %}
        {% endfor %}
    {% endfor %}
{% endfor %}

This works, however, since the checking occurs after I get all the entries I can't use pagination. Is there a nicer way of doing this?


texts:
I've been looking at http://straightupcraft.com/articles/the-definitive-guide-to-validation-in-craft which seems to concentrate on custom models. However I am looking to validate data posted to a plugin that stores that data as core EntryModels.

So let's say you create a Section and assign some Fields in its field layout. You can set each Field to be required but I want to do more than that and check if it's an integer or if it's unique.

I am currently doing that in my service class:

private function validateReference()
{
    $reference = craft()->request->getPost('reference');

    $existingEntryCount = craft()->elements->getCriteria(ElementType::Entry)->total(array(
        'reference' => $reference
    ));

    return ($existingEntryCount === 0);
}

That all works but I am wondering if instead I should be setting the validation properties of each Field in this service and then just running a core validate method?


texts: Element API: Is it possible to ignore/skip an Entry?

texts:
I would like to exclude some of my entries, via my own validation inside the Transformer, from the api output.

Is there a possibility to move on to the next Entry without outputing anything? Right now im just returning an empty array, but i think it would be cleaner to return nothing.


texts: How to programmatically translate an entry in craft 3

texts:
I'm trying to write a plugin that translate entries programmatically based on subsites that have different language setup.
Normally what happens is this: you setup multi-site, set each sub-site as having a different language and a different url (like @web/de, @web/sv etc), you set a field as translatable by language, then you edit an entry on each of those sub-sites. And the system knows to separate entries by siteId.
Now, I tried the same approach programmatically. I get all the entries for all the subsites like this:
$sites = Craft::$app->getSites()
                    ->getAllSites();
/** @var Entry[] $entries */
$entries = [];
foreach ($sites as $site) {
    /** @var Entry $entry */
    $entries[$site->language] = Entry::find()
                                     ->id($id)
                                     ->siteId($site->id)
                                     ->one();
}

The I go and get all the fields for the English entry (in my setup is safe to assume that all the sub-sites respect the same field layout/structure). To test this, I dumped the values to compare the English version of the field, with the Swedish version. Values were different, which means I'm looking at the correct fields for the correct sub-entry.
//this is how we get the english fields
$fields = $entries['en']->getType()
                        ->getFieldLayout()
                        ->getFields();

//this is how we translate each field for each language
foreach ($fields as $field) {
    if ($field->translationMethod === \craft\base\Field::TRANSLATION_METHOD_LANGUAGE) {
        //get english value
        $enValue = $entries['en']->getFieldValue($field->handle);
        if (!empty($enValue)) {
            //translate in all languages
            $translations = $this->translate($enValue, array_keys($entries));
            foreach ($entries as $lang => $entry) {
                $fieldValue = $entry->getFieldValue($field->handle);
                //only translate if the destination language/field is in English (not translated yet)
                if (('en' !== $lang) && !empty($enValue) && ($enValue === $fieldValue)) {
                    if (!empty($translations[$lang])) {
                        //setFieldValue for each language
                        $entry->setFieldValue($field->handle, $translations[$lang]);
                    }
                }
            }
        }
    }
}

This is how I try to save the entries at the end of it all
//save all non-eng entries
$elements = new Elements();
foreach ($entries as $lang => $entry) {
    if (('en' !== $lang) && !$elements->saveElement($entry)) {
        echo json_encode($entry->getErrorSummary(true));
        die();
    }
}

The issue is that it saves the last translated language in all the sub-sites, for some reason, and I don't understand what I'm doing wrong.


texts: Show related entries that have the same Category, and some of the same tags?

texts:
I have succesfully shown some related entries that are in the same category, using the following:

{% set relatedEntries = craft.entries({
    section: 'blog',
    relatedTo: entry.blogCategory.first(),
    id: 'not ' ~ entry.id,
    limit: 3
}) %}

(Entries generally only have 1 category on this site).

What I would like to do next, is look for entries that have some of the same  tags as the current entry, making this list of entries even more relevant.

Essentially I want the related entries to be as relevant as possible, this could even go as far as ignoring the Category if there are more tags in common, is that possible by somehow grading the results and displaying the most 'in-common' entries?


texts: Would you use a Structure as navigation over multiple sections (channel entries, indexes and singles)?

texts:
I'm setting up my first Craft project and I have a lot of different content. I have around 6 different Channels (News, Events, Blog, Pages, Products, Staff) and ~10 Singles.

I have this idea of using Structures as my sorting and "Navigation" "content types" only. Meaning I'll for example have one Structure called "Navigation" in which I have the default "Title" field and one "Entries" field (for linking to other entries in channels and singles). This I'll output in my template and fetching each linked entries page.link to build my main site navigation.

This should give my client the ability to control the main navigation structure of the entire site 100% with sorting, linking and naming each navigation item ("Title").

Is this a good approach on using a Structure this way? Or will the extra field "Entries" give me a massive query count when the Structure contains (let's say) 100 entries?


texts: Is there a way a plugin can watch for live preview updates?

texts:
I'm working on a site that involves taking a URL and then getting information about that URL using an API. The URL is entered into a field in a Matrix block, and then another field in the same Matrix block is populated automatically on save. This is working, but only when the article is saved. I'd also like it to work in live preview mode. The event I'm using on save is entries.saveEntry, but I've also tried using entryRevisions.onSaveDraft, hoping that drafts were saved with live preview changes, but that didn't work.

Question:
Is there some event I can listen for that lets me know when the live preview is about to refresh? Can this be done with JavaScript in the admin instead? If so, is there documentation that describes how to do this?


texts: Is there a method to remove the ability for commerce to allow guest accounts? I want to allow only registered, logged-in users to be able to place orders.


texts: How do I call the getInputHtml() method of a custom fieldtype plugin from another plugin?

texts:
Plugin 1

I have a plugin that is a custom fieldtype.  It works fine, and has a getInputHtml() method that behaves as expected.

Plugin 2

Now, I have a second plugin, where I want to output the HTML from the Plugin 1 getInputHtml() method.

I have the FieldModel:

$field = $field->getField();

I have the Plugin 1 fieldtype object

$fieldtype = craft()->fields->populateFieldType($field, $element);

And I call the getInputHtml() method:

$fieldtype->getInputHtml($field->handle, $value);

If I place the necessary files at the base of Plugin 2 plugin2/templates/plugin1/_field/input everything works fine.  But I can't seem to access the input HTML template in the context of Plugin 1: plugin1/templates/_field/input

I've tried to update the Template Path in various ways before calling $fieldtype->getInputHtml():

craft()->path->setTemplatesPath(craft()->path->getPluginsPath());
craft()->path->setTemplatesPath(craft()->path->getPluginsPath() . 'plugin1/');
craft()->path->setTemplatesPath(craft()->path->getCpTemplatesPath());

Everything I have tried has resulted in a template error:

Unable to find the template "plugin1/_field/input".

Any ideas on what I'm doing wrong?


texts: Unable to retrieve a cookie set by another application on the same domain

texts:
We have a Laravel app that sets a cookie:

public function make($name, $value, $minutes = 0, $path = null, $domain = null, $secure = false, $httpOnly = true)
{
    list($path, $domain) = $this->getPathAndDomain($path, $domain);

    $time = ($minutes == 0) ? 0 : time() + ($minutes * 60);

    return new Cookie($name, $value, $time, $path, $domain, $secure, $httpOnly);
}

The values passed are as follows:

array (size=7)
    0 => string 'imph_auth' (length=9)
    1 => string 'Russ Back' (length=9)
    2 => int 2628000
    3 => null
    4 => null
    5 => boolean false
    6 => boolean true

I've tried to retrieve that cookie in a Craft template as follows:

craft.request.getCookie('imph_auth')

However I get null when I know that it's been set (I can browse to a Laravel template on the same domain and get the cookie).

I note the JavaScript warning in the Craft docs but this is set in PHP, however I can see the getCookies() method of the CookieCollection class runs each cookie through craft()->security->validateData() and fails validation.

Is there any way I can get around this without resorting to my own PHP in the template or a custom plugin?


texts: How to integrate custom statuses in a workflow style custom element type?

texts:
I made a lot of progress on my custom element type from this post and with the help of @selvinortiz:

Best way to implement my own statuses on my custom element type?

I know have custom statuses that look like this:

However, there are a few things I'm stuck on:

How do you assign colors to the statuses? I could target them with CSS but I feel there may be a way with Craft itself.
When listing entries in my templates, the default status is "green" for enabled. So how do I correlate my custom statuses with the enabled/disabled featured thats all ready in place?

I feel like Craft is the perfect tool for developing a workflow style plugin but I am having a few issues with statuses specifically. Does anyone have personal experience with creating a workflow, using native functionality, with Craft?


texts: I have a section (events) with a Super Table field that has a date field. I am looking for a way to make a request to have the events superior to now. I cannot find how to do it. The event have multiple dates. Thanks for your help.


texts: Can't login after installing Craft CMS 3

texts: I just installed Craft CMS 3 and I tried logging in as my admin user but it's not working. I enter the correct login information and nothing happens. I tried the reset password option but never got the email for some reason. Anyone have any ideas what is going on?


texts: Listen to replacing files through CP's assets section

texts:
Admin users can replace asset files without having to deal with re-uploading/re-creating a new asset using the feature/technique described in Peter's answer here: Is it possible to replace uploaded assets?. This has the advantage of preserving any values in the asset's custom fields.

I need to populate some of those fields dynamically though, so they correspond to the new file for the asset. So, I wrote a small plugin that listens to the assets.onReplaceFile event like so:

craft()->on('assets.replaceFile', function(Event $event) {
  Craft::dd($event->params); // or whatever
});

But the code in the handler never gets executed. Is this the right event to listen to this specific user action or is there another event for it? Or am I doing something wrong here? Thanks!


texts: How to check if currentUser matches a users field within an entry?

texts: I've already found the entry, and the 'users' field can contain multiple users.


texts: How would I detect whether an entry's asset field has been updated on save?

texts:
We need to send a notification email when an entry's asset field, Custom Image, has been updated on entry save. We're able to do this consistently for text fields but I'm having trouble doing the same for an asset field.
// Use statements etc

...

// Register the event handler
Event::on(Entry::class, Entry::EVENT_AFTER_SAVE, [$this, 'handleAfterSave']);

...

public function handleAfterSave(ModelEvent $event): void
{
    $entry = $event->sender;
    $revisions = Entry::find()->revisionOf($entry)->status(null)->orderBy('revisionId DESC')->all();
    $lastRevision = Craft::$app->getElements()->getElementById($revisions[1]->id);

    $fields = Craft::$app->getFields();

    // text fields
    $notificationHandles = [
        'textField1',
        'textField2',
    ];
    $updatedFields = array_map(
        fn ($h) => [
            'fieldName' => $fields->getFieldByHandle($h)->name,
            'oldValue' => $lastRevision[$h],
            'newValue' => $entry[$h],
        ],
        // Only need to show field if different from last revision
        array_filter($notificationHandles, fn ($h) => $lastRevision[$h] !== $entry[$h])
    );

    if (count($updatedFields) > 0) {
        self::$notifications->notifyUpdated($entry, $updatedFields);
    }
}

The above works for text fields. However, when adapting for an asset field, it appears that $lastRevision[$h] is not immediately updated.
If we have an entry with an empty Custom Image asset field:

Assign an image to Custom Image
Save
Email is sent
Return to the entry
Remove the asset from Custom Image
Save
No email is sent

To put it another way, if I have an entry with an empty Custom Image field:

Assign an image to Custom Image
Save
Email is sent
Return to the entry
Remove the asset from Custom Image
Save, but dump $lastRevision using EVENT_AFTER_SAVE
We can see that customImage is still null, where I would expect it to show the previously attached image (an AssetQuery etc)
No email is sent because both $lastRevision['customImage'] and $entry['customImage'] are null.

Thanks!


texts:
I’ve set up a multilingual craft site.
My primary site is BE and base Url is set to /
The two other ones are NL which base Url is set to /nl and LU which is set to /lu
All the three website have en-US as a language.
When I google my website and I say I speak Dutch, the only website that is showing is the NL version. It’s not even showing the BE or LU version.

Any way I can change this?

Thanks in advance!


texts: Error: Variable 'entry' does not exist - When adding homepage or other entry with URL

texts:
I have an existing Craft Pro installation (v2.5.2757) that I'm using to drive an application.  The current install does not have a homepage or any entry associated with a URL. All requests are being handled by Dynamic Sites Routes (routes.php).

The site has been running without issue for months with edits being made to entries and content being updated in the application.

However, when I went to create a homepage for the site, I would receive the following error when the site loaded:

I confirmed that the 'This is for the homepage' was checked and that the correct 'Entry Template' was entered. I suspected that something in routes.php was causing the issue, but cleared that out and still received the error.  I tried clearing the caches as well but no luck.

After multiple hours of troubleshooting I'm at a loss.


texts: Using “search” vs. “relatedTo” in a template

texts:
I have problems to understand the difference between search and relatedTo. From my understanding, this is a fulltext search on all fields.

{% set entries = craft.entries.search(test).order('score') %}

Does the following approach mean the same?

{% set entries = craft.entries.relatedTo(test).order('score').find() %}

And if yes, which one delivers the better performance?

Thanks!


texts:
I have Event entries which contain (among other things) a SuperTable holding the schedule for that event.  Each row of the SuperTable contains (among other things) a field for a Session entry, in a column called sessions.  A Session entry contains (among other things) a field for a Person entry, called sessionSpeaker, who is the speaker for that session.  I also have a list of (usually) the same speakers in an Entries field outside the SuperTable; this is called eventSpeakerList.
What I’m trying to do is, for each speaker, find the ID of their session so I can output it as part of a hyperlink in a preview grid of speaker cards which points to the session in the detailed agenda.  So…
{% set speakers = entry.eventSpeakerList.all() %}
{% for speaker in speakers %}

[something something something]

<a href="#s{{ sessionID }}">
{% endfor %}

The problem is, I can’t figure out how to do the [something something something] to get the ID of a session based on the ID of the speaker.  When I say ID here, I meant the Craft ID, not a bespoke ID text field or whatever.
I’ve tried relatedTo() queries on the table, but never get anything back, probably because I didn’t structure the queries correctly.  I’ve tried search() queries; again, nothing.  Or, in some cases, massive object structures that didn’t contain anything I could figure out how to use.  I also tried looping through rows and trying to peer into the fields within fields, but couldn’t figure out how to make that work either.  I’ve searched this SE for similar questions, but the posts I found that seemed similar either had answers I couldn’t make work (again, quite possibly due to inexperience), or had no answers at all.
Maybe there’s a really simple way to do this and I can’t see it, or maybe it requires relation queries and I’m too inexperienced to understand how to structure them, or who knows.  But I could really use some help.  Let me know if you need clarifying details on the above, and I’ll edit them in.
--
EDIT: here’s a screenshot from the admin interface showing the supertable and the fields within fields.


texts:
I have the same error in here.

Craft info says i have installed the ImageMagick extension successfully  and even use ‘imageDriver’ => ‘imagick’ in config file. But still cant upload GIF files.


texts: trying to use loop.length with some dynamic css

texts:
I'm using CSS calc to help make my links the proper width and still account for the margins that separate them. The number of links here will vary between 3 and 5 and I wanted to not have to update my CSS when this changes. The code below works except the code is written after CSS is run and therefore doesn't set the width for the links as I'd want. Is there a way to get this to work using Craft or is this a problem with the way calc works?

{% set contactLinkCSS %}
    {% for block in contactLinks.contactLinks.type("contactLink") %}
        {% set count = 100 / loop.length %}
        .{{ block.contactLinkName | slugify }}:hover {
            width:calc({{ count }}% - 0.625rem);
            background-color: {{ block.contactLinkColor }}
        }
    {% endfor %}
{% endset %}


texts: Blank screen for /admin and public site with Craft 3

texts:
I've just installed Craft 3 RC with Composer. Everything went fine. I moved the contents of the web directory to the public_html folder.

domain.com/admin
and
domain.com

both give blank screens. Where should I start my troubleshooting?

Folder structure

.composer
craft
  config
  modules
  storage
  etc...
public_html
  /cpresources
  .htaccess
  index.php
  web.config
  test.php

If I add an index.html to the public_html folder, I can access it via domain.com, but I cannot access domain.com/test.php from public_html.

Thanks,
Ben


texts: How do I hide notifications about running tasks?

texts:
I installed Import.  I tried to run a test import and it froze.   Now the pop-up status that appears in Craft's menu - just below Settings - will not disappear.

I even uninstalled the plugin.  But, the status notification is still in the menu.   It's driving me nuts.

How do I get rid of it?   At this point, I don't care about getting import to work or not.

(Oh, and there were no image transforms with the test import - it was only 21 lines of a simple css file.)


texts: Get Entrys relationships regardless of context

texts:
This might be a little complex, but here it goes:

Goal: For any given entry, determine where it's located. (Ex. Entry XYZ exists in a news entry, global field, single (page), etc...)

Context:
So far I figured I could go the custom SQL route until I learned more about craft internals, so what I did was create a Service that does the following query:

    $query = craft()->db->createCommand()
        ->select('element.*, detail.type, relation.fieldId AS sectionId, section.handle, section.name, section.hasUrls')
        ->from('elements_i18n AS element')
        ->join('relations AS relation', 'relation.sourceId = element.elementId')
        ->join('elements AS detail', 'detail.id = element.elementId')
        ->join('sections AS section', 'section.id = relation.fieldId AND section.hasUrls = 1')
        ->where('relation.targetId = :id', array(
            ':id' => $elementID
        ));

    $results = $query->queryAll();
    $results = MyPlugin_EntryRelationshipModel::populateModels($results);

I'm using MyPlugin_EntryRelationshipModel as a Facade and it extends Craft\ElementCriteriaModel

Problem: This works flawlessly until a Matrix field comes into play.


texts: Craft 3 How to get custom user field values

texts:
I have following custom fields for users.

favouriteEntries - 'entry' type field with multiple entries per user
notificationPreference - Lightswitch field

My plugin should email notifications to users who follow that entry when there is an update to a particular entry (Entry::EVENT_AFTER_SAVE).

use craft\elements\User;

$users = User::find()->all();

With the above code, I can get all user data including notificationPreference but favouriteEntries. favouriteEntries field returns null even if it has entries for all users.

What's the correct way to get all user data including favouriteEntries field?


texts: Is this a basic error, or do I misunderstand how Craft queries the database?

texts:
I’ve been wrestling with a site from another developer (who will not be named). He seems to have a pretty solid grasp of PHP, and I had assumed that he also understood Craft well.
However, as I started to look at his templates, I came across code like this:
{% if
  (entry.productDimensionsImage.one() or
   entry.productSpecifications.one())
%}

I would have written it using count() instead of one(), or if I really needed the entry:
{% set prodDim = entry.productDimensionsImage.one() %}
{% set prodSpc = entry.productSpecifications.one() %}
{% if (prodDim and prodSpc) %}

My main concern is that the exact same queries are being used repeatedly throughout a single template; he’s going back to the database over and over again to check the same entry. Then, after he’s done so half a dozen times, then he finally sets it in a variable to loop through it.
So, is there something I’ve misunderstood? Is there a good reason to keep querying the database multiple times in a single template file?
TIA


texts: Hide search results depending on field value

texts:
This is my search results query:

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

I have a lightswitch field called showInSearch. When it is set to 1 the entry should not appear in search results.

Problem
When I do this I always get zero results on my searches:

{% set query = craft.request.getParam('q') %}
{% set miniCards = craft.entries.search(query ~' -showInSearch:1').order('score').limit(12) %}

Whereas when I do the opposite I get all results with the search term and the lightswitch field set to 1.

{% set query = craft.request.getParam('q') %}
{% set miniCards = craft.entries.search(query ~' showInSearch:1').order('score').limit(12) %}

I also tried -showInSearch::1,-showInSearch::"1", -showInSearch:"1" and showInSearch:0 to no avail. What am I doing wrong?

Problem persists even after rebuilding search indexes.


texts: Dukt Twitter Plugin, problem with "search/tweets" or request to Twitter REST API

texts:
we're using the Dukt Twitter plugin 0.9.25 and it works fine with calling the user's timeline:

    {% set tweets = craft.twitter.get('statuses/user_timeline', {count:1}) %}

If we request any other data like

    {% set tweets = craft.twitter.get('search/tweets', {q:'#craftcms',}) %}

we're receiving two tweets which are empty. Anyone else having these problems and found a solution?

Thanks, Lars


texts:
I thought this was going to be easy; showing the order number of children against their parent, but the only answer I can find is in this thread

and I'm unsure how to implement this into my code.

{% for chapter in entry.descendants %}

Part {{ chapter.orderNumber | numbersToWords }}

{% endfor %}

Resulting in: Part One

Note: numbersToWords is the Helpers Plugin by carlcs


texts: Last header tag overwrites any previous tag with same name - expected behaviour?

texts:
I am trying to add several header tags with the same name but different values. The last one prevails where the other don't appear to be output (when examining the output header using a sniffer). eg.

{% header "Link: </css/master.css>; rel=preload; as=style" %}
{% header "Link: </js/plugins.js>; rel=preload; as=script" %}
{% header "Link: </js/main.js>; rel=preload; as=script" %}

I'm trying to implement HTTP/2 server push for these files. Is this expected behaviour? Thanks


texts: Using a custom Commerce 2 Adjuster in a Craft Plugin

texts:
I wrote a little commerce 2 price adjuster that works fine if i place it in
/vendor/craftcms/commerce/src/adjusters/FriendsDiscountAdjuster.php and register it manually in /vendor/craftcms/commerce/src/services/OrderAdjustments.php

However, i wanted to port it to a plugin, but i do fail registering the adjuster to commerce.

I placed the adjuster in my vendor/pluginName/src/adjusters/ folder
and added it to my plugin.

It fails with:
Cannot declare class craft\commerce\adjusters\FriendsDiscountAdjuster, because the name is already in use

this is my main plugin file Friendsdiscount.php:

<?php
namespace hendrikeng\friendsdiscount;

use Craft;
use craft\base\Plugin;
use craft\services\Plugins;
use craft\events\PluginEvent;
use craft\commerce\services\OrderAdjustments;
use craft\events\RegisterComponentTypesEvent;
use hendrikeng\friendsdiscount\adjusters\FriendsDiscountAdjuster;

use yii\base\Event;

class Friendsdiscount extends Plugin
{
    public static $plugin;

    public $schemaVersion = '1.0.0';

    public function init()
    {
        parent::init();
        self::$plugin = $this;

        Event::on(
            OrderAdjustments::class,
            OrderAdjustments::EVENT_REGISTER_ORDER_ADJUSTERS,
            function(RegisterComponentTypesEvent $event) {
                $event->types[] = FriendsDiscountAdjuster::class;
            }
        );
    }
}

the src/adjusters/FriendDiscountAdjuster.php:

<?php

namespace craft\commerce\adjusters;

use Craft;
use craft\commerce\base\AdjusterInterface;
use craft\commerce\elements\Order;
use craft\commerce\models\OrderAdjustment;
use craft\commerce\Plugin;

class FriendsDiscountAdjuster implements AdjusterInterface
{
  // ...Adjust something
}


texts: How are people organizing their global sets?

texts:
I've found it a little challenging to use global sets effectively, so I'm wondering how others are doing it.

The fact that a global has to be in a set has been a little tricky to deal with at the beginning a of a build, as knowing what those sets might be is hard when there aren't any globals yet.

This leaves me using sets like "Misc", "Content", and "Settings", which doesn't end up being all that helpful.

The arbitrary nature of these assignments also present a problem when using those globals, because you have to call them with their set name {{ settings.analyticsId }}.

Just thinking out loud, and wondering how others are dealing!


texts: Locale Switch not Affecting News Index Template

texts: So I have successfully set up two locales on my site, with a button to switch between, this works fine for all the sections that have the langauges set, but I cannot seem to get it to work for the news index template, my news feed. An individual entry will work fine, but the collated entries don’t. Is there a snippet I need to place at the top of the News index template to define what locale it should contain?


texts: Database issue on upgrade to 2.5 on shared hosting

texts:
I have a problem with upgrading to Craft 2.5 on a shared hosting platform. I have run the upgrade both automatically and also tried manually. It runs but when I try to update the database I get a fatal error message telling me to contact my server providers.

I believe the problem is the size of the database as there are 20000+ users and related user data. So it's 43mb which I think the shared hosting is having issues with.

As I am limited to what PHP limits I can change with shared hosting I am looking for a workaround.

My first thought is to empty the user tables from the database (which would reduce the size considerably), run the update and then add them back in. However I wanted to check if there were any database changes to the user tables in the upgarde. I'm looking at using version 2.5.2761

I've looked through the change log but can't see anything obvious.

Has anyone else come across this issue or are there any other better solutions?

Cheers


texts:
First time using the Imager plugin and really unsure how to code it. Looking over the documentation I'm not clear on what the 'logo' is referring to to know what to change it to:

{ watermark: { image: logo, width: 80, height: 80, position: { right: 30, bottom: 30 }, opacity: 0.8, blendMode: 'multiply' } }

https://github.com/aelvan/Imager-Craft

My attempt so far:

{% set imageWatermark = [{ watermark: { image: logo, width: 80, height: 80, position: { right: 30, bottom: 30 }, opacity: 0.8, blendMode: 'multiply' } }] %}

{% set transformedImages = craft.imager.transformImage(image, imageWatermark) %}

{# Output image #}
<img src="{{ asset.getUrl('transformedImages') }}">


texts:
So I've setup locales following the official guide and am going with the option where English (en_gb) is the default and Danish (da_dk) is in a sub-folder:

http://mysite.com      --> en default
http://mysite.com/dk/  --> dk sub-folder

In summary, I've set the locales in Settings -> Locales

I've enabled them for my section (which is a channel):

I've set the siteURL array (single domain config):

'siteUrl' => array(
    'en' => 'http://mysite.com',
    'dk' => 'http://mysite.com/dk/',
),

I've created the folder structure and copied the index.php file and .htaccess file across to the dk/ folder:

craft/
public_html/            --> mysite.com/
    .htaccess
    index.php
    dk/                 --> mysite.com/dk/
        .htaccess
        index.php

And I've made the edit to the dk/index.php file:

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

// Tell Craft to serve the Danish content
define('CRAFT_LOCALE', 'dk');

Viewing my entry in English works fine:

http://mysite.com/segment/title  --> Shows in English

Viewing the same entry in Danish directs to:

http://mysite.com/danishsegment/title --> Missing /dk/ in URL. Nothing shown

So the preview link for Denmark doesn't include the country segment in the URL (dk/) and results in a 404. Even manually adding dk/ to the URL results in a 404. It doesn't seem to be recognising the Danish locale at all.

Any ideas as to what I'm doing wrong?

UPDATE:

Here are the contents of my .htaccess files. All standard Craft with a Type to ensure PHP 5.6 is used:

AddType x-httpd-php56 .php

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

UPDATE 2:

The 'Offers' section (Channel) is set to have a different URL for each Locale:


texts: Cached template content not invalidating

texts:
My understanding of the {% cache %} tag is that if the content between it changes, the cache is invalidated and you see the new content.

I'm having an issue where a new entry is created in section, but it doesn't show up on the front-end unless I manually clear the cache in the control panel.

The content is pulled in via a loop such as:

{%  for entry in craft.entries.section( "news" ).limit(3) %}

Am I not understanding how this tag works or is something going wrong?

Edit: Here is the full code block wrapped by cache tags

{% cache %}
{%  for entry in craft.entries.section( item.nameId ).limit(3) %}

{{ entry.title }}

                    {% if item.type == "video" %}
                        {% set iconType = "icon-video" %}
                    {% elseif item.type == "game" %}
                        {% set iconType = "icon-games" %}
                    {% elseif item.type == "image" or item.type == "imageGallery" %}
                        {% set iconType = "icon-image" %}
                    {% else %}
                        {% set iconType = "icon-paper" %}
                    {% endif %}

{% endfor %}
{% endcache %}

The strange thing that I'm noticing is if I add an entry it never shows up, but if I delete one it does get cleared out. And deleting an entry then causes the new one to show up.

UPDATE: Craft support determined there was a bug and plans to fix it in the next version. Current version is Craft 2.1 build 2563.


texts: Poor performance on midsized site / Queries without index?

texts:
I'm running a mid sized website (couple hundred articles, between 30-50k visits per day) on a Digital Ocean 16GB / 8 Cores web server and I have two questions:

Most of the time the website runs smoothly, however, several times per day MySQL starts using all of the CPU and I see a spike on disk IO.

Running show process list on MySQL shows that most queries are "Copying to tmp table"  and look like this

I'm new using Craft and I want to know is this queries are normal and if there's a way to optimize them:

    EXPLAIN SELECT `elements`.`id`, `elements`.`type`, `elements`.`enabled`, `elements`.`archived`, `elements`.`dateCreated`, `elements`.`dateUpdated`, `elements_i18n`.`slug`, `elements_i18n`.`uri`, `elements_i18n`.`enabled` AS `localeEnabled`, `content`.`id` AS `contentId`, `content`.`title`, `content`.`field_airingDate`, `content`.`field_airingFrom`, `content`.`field_airingTo`, `content`.`field_awsPath`, `content`.`field_descripcion`, `content`.`field_descripcionSocialMedia`, `content`.`field_subtitulo`, `content`.`field_texto`, `content`.`field_titulo`, `entries`.`sectionId`, `entries`.`typeId`, `entries`.`authorId`, `entries`.`postDate`, `entries`.`expiryDate`, `structureelements`.`root`, `structureelements`.`lft`, `structureelements`.`rgt`, `structureelements`.`level`
    FROM `elements` `elements`
    JOIN `elements_i18n` `elements_i18n` ON elements_i18n.elementId =         elements.id
    JOIN `content` `content` ON content.elementId = elements.id
    JOIN `entries` `entries` ON entries.id = elements.id
    JOIN `sections` `sections` ON sections.id = entries.sectionId
    LEFT JOIN `structures` `structures` ON structures.id = sections.structureId
    LEFT JOIN `structureelements` `structureelements` ON (structureelements.structureId = structures.id) AND (structureelements.elementId = entries.id)
    WHERE (((((elements_i18n.locale = 'es') AND (content.locale = 'es')) AND (elements.archived = 0)) AND ((elements.enabled = 1) AND (elements_i18n.enabled = 1) AND (entries.postDate <= '2017-04-11 16:56:24') AND ((entries.expiryDate is null) OR (entries.expiryDate > '2017-04-11 16:56:24')))) AND (elements_i18n.enabled = 1)) AND (sections.handle='articulos')
    GROUP BY `elements`.`id`

Another example:

    SELECT count(`derivedElementsTable`.`elementsId`)
    FROM (SELECT `elements`.`id` AS `elementsId`, `entries`.`sectionId`, `entries`.`typeId`, `entries`.`authorId`, `entries`.`postDate`, `entries`.`expiryDate`
    FROM `elements` `elements`
    JOIN `elements_i18n` `elements_i18n` ON elements_i18n.elementId = elements.id
    JOIN `content` `content` ON content.elementId = elements.id
    LEFT JOIN `relations` `sources1` ON (sources1.targetId = elements.id)
    LEFT JOIN `relations` `targets1` ON (targets1.sourceId = elements.id)
    JOIN `entries` `entries` ON entries.id = elements.id
    JOIN `sections` `sections` ON sections.id = entries.sectionId
    LEFT JOIN `structures` `structures` ON structures.id = sections.structureId
    LEFT JOIN `structureelements` `structureelements` ON (structureelements.structureId = structures.id) AND (structureelements.elementId = entries.id)
    WHERE (((((elements_i18n.locale = 'es') AND (content.locale = 'es')) AND (elements.archived = 0)) AND ((elements.enabled = 1) AND (elements_i18n.enabled = 1) AND (entries.postDate <= '2017-04-11 16:56:33') AND ((entries.expiryDate is null) OR (entries.expiryDate > '2017-04-11 16:56:33')))) AND (elements_i18n.enabled = 1)) AND ((sources1.sourceId='175') OR (targets1.targetId='175'))

I understand that the i18n tables are where the locales data is stored. Is there a way to disable a locale without losing any data?


texts: What's the easiest way to generate a link to edit a given entry in Craft?

texts:
Assuming I am fetching an entry like so:

{% set profile = craft.entries.id(8268).one %}

What is the easiest way to generate a link that allows you to edit that entry in Craft? I know you can do the following:

{{ siteUrl ~ 'admin/entries/profiles/' ~ profile.id }}

But surely there must be a better way?


texts: Craft 3 best way/steps to create a login client area in frontend

texts:
I have to make a website that needs an user area with login.

In that area users should be able to upload to admin area or download files from admin area.

Each user has its own account that is separate from other users.

I used to work with cake framework but in the several past weeks i made a few projects in craft cms 3 and liked it due to the easy and fast time to go up and running a full stack website.

Is it possible to make the users area in the frontoffice of craft cms 3?

If it is, there is a plugin available to do it (i searched and didn't find one), or can somebody point me the steps that are needed to do it?

Many thanks.


texts: I am working on LivePreview and the window it's get loaded at every change. It is possible to do that only when I will click the Save button?


texts: Searching for item SKU in Commerce orders

texts:
I'm trying to show some Commerce 2 order information on the front-end. I can't work out the correct syntax. I'm trying to list orders that include a specific product.

I have orders for item SKU "abc123" but this is returning no results.

{% set myOrderQuery = craft.orders()
    .relatedTo("abc123")
    .limit(10)
    %}

{% set orders = myOrderQuery.all() %}

{% if orders|length %}

    {% for order in orders %}
      {% for item in order.lineItems %}

{{ item.sku }}

      {% endfor %}
    {% endfor %}

{% else %}

No results

{% endif %}

If I remove the .relatedTo parameter I get results including orders for that item. How do I just return orders that include that item?

I've tried various permutations of relatedTo and search but haven't found anything that works yet.


texts:
Can't view image assets in web browser (403 error) after uploaded in Craft CMS Dashboard.

I've checked permissions according to previous thread:
403 Forbidden Assets

Help please!


texts: How to process Matrix field in controller

texts:
I am trying to process a text field inside a Matrix field.

In the controller I have this to get posted params:

$element->setFieldValuesFromRequest($fieldsLocation);

If I want to process a custom text field, I can do it easily with

$result=$element->getFieldValue('textFieldHandle')

which $result is exactly the text field value.

but if I have this text field in Matrix field, if I do this:

$result=$element->getFieldValue('matrixFieldHandle')
craft::dd($result)

I get a craft\elements\db\MatrixBlockQuery object which I don't know how I can fetch text value from this object.


texts: Best way to handle large amount of records

texts:
What is the best way to handle 20,000 simple records?  The records need to be searchable and linked to categories.  What is the best way to handle so many records when each records or entry would be a simple phrase 5-10 words max.

I thought of categories but thinking 20k anything has to be thought out.  Since categories may or may not be most efficient, any ideas or way that you have done this in the past before with success?


texts: How do you correctly handle errors using PT Contact Form when submitting via AJAX?

texts:
I'm trying out AJAX submission for the PT Contact Form for the first time. I've managed to get errors appearing on the frontend, but I don't feel like I'm doing it the right way. It also doens't integrated at all with the {% macro errorList(errors) %} code that comes with the form. This is my form JS:

$(function(){
    $('#ajax-form').submit(function(ev) {
        // Prevent the form from actually submitting
        ev.preventDefault();

        // Get the post data
        var data = $(this).serialize();

        // Send it to the server
        $.post('/', data, function(response) {
            if (response.success) {
                $('#thanks').fadeIn();
            } else {
                // response.error will be an object containing any validation errors that occurred, indexed by field name
                // e.g. response.error.fromName => ['From Name is required']
                if (response.error.fromName) {$('ul.errors').append('
'+response.error.fromName+'
');}
                if (response.error.fromEmail) {$('ul.errors').append('
'+response.error.fromEmail+'
');}
                if (response.error.subject) {$('ul.errors').append('
'+response.error.subject+'
');}
                if (response.error.message) {$('ul.errors').append('
'+response.error.message+'
');}
            }
        });
    });
});

Form code:

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

    {% for error in errors %}

{{ error }}

    {% endfor %}

{% endif %}
{% endmacro %}

{% from _self import errorList %}

<form method="post" action="" accept-charset="UTF-8" id="ajax-form">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="contactForm/sendMessage">
    <input type="hidden" name="redirect" value="/contact">

    Name *
    <input class="form-control" id="fromName" type="text" name="fromName" value="{% if message is defined %}{{ message.fromName }}{% endif %}">
    {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

    Email *
    <input class="form-control" id="fromEmail" type="text" name="fromEmail" value="{% if message is defined %}{{ message.fromEmail }}{% endif %}">
    {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

    Subject
    <input class="form-control" id="subject" type="text" name="subject" value="{% if message is defined %}{{ message.subject }}{% endif %}">
    {{ message is defined and message ? errorList(message.getErrors('subject')) }}

    Message *
    <textarea class="form-control" rows="10" cols="40" id="message" name="message">{% if message is defined %}{{ message.message }}{% endif %}</textarea>
    {{ message is defined and message ? errorList(message.getErrors('message')) }}

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

I've had to put a blank

 under my form, as the .error ul that comes with the contact form doesn't appear. Where am I going wrong?

Desired result: I get exactly the same error handling as I would if I wasn't submitting via AJAX - i.e., the error messages relating to specific fields appear under those fields in the form.


texts: How can I separate assign user groups and permissions for users?

texts:
I've been here before Users allocating permissions beyond their own and the only solution offered was to vote for it as a feature request, which I did. But after 7 months there have only been 10 votes for it.

I can't understand how so few people find this a problem.
You need to give someone the ability to add users and put them in a suitable user group, but you then give them a free pass to increase their own access permissions and potentially reduce the access permissions for me the prime admin, this can't be acceptable for any user management system.

I need to have an administrator role that can register users and put them into suitable groups, but not let that person manage the permissions for themselves or others.

The most obvious option is to separate "assign user groups" from "assign user groups and permissions"


texts:
I'm struggling to figure out how to map an array of values in a plugins settings to a group of checkboxes:

protected function defineSettings()
{
    return array(
        'createGlobals' => array(
            AttributeType::Mixed, 'default' => array(
                "twitter" => true,
                "facebook" => true,
                "linkedIn" => true
                )
            )
        );
}

Here's one checkbox in my plugins template:

{{  forms.checkboxField({
  label: "Twitter"|t,
  name: '???',
  value: 'on',
  checked: settings.createGlobals.twitter
}) }}

As you can see, I've omitted the name value. Is there any way of mapping this name to the settings.createGlobals object?


texts: /login page in Craft keeps redirecting to home page. What could be causing that?

texts:
I have a structured channel setup to house all the static pages on the site. All of the pages display fine on the page entry template. But the /login page does not. It displays fine in Live Preview. But on the actual site it immediately redirects to the homepage.

Is /login a protected keyword or something?

My .htaccess file is quite normal

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)/$ /$1 [L,R=301]

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

And I have the Sprout SEO plugin handling some basic redirects. I'm at a loss to know where to even look next.  Any ideas?

This isn't a login form to get into Craft by the way. It's to login to a separate website entirely.


texts: Multiple Sections Within a Structure Group?

texts:
My site has a set of different layout types with their own templates:

Brochure
Listing
Plain Text

And the site has a group of hierarchical pages that each use a different layout:

About (Brochure Layout)

Employees (Listing Layout)
History (Plain Text Layout)

So I've got these 3 pages each with different content and layout requirements that all need to be grouped together under the "About" page. But I can only use one Section type per Structure.

I don't want to use Entry Types, because I need to use the layouts in multiple places on the site. For example there's a Brochure-type page in the site's 'Careers' area. If something about the layout changes I don't want to have to go through multiple Entry Types to make the changes over and over.


texts: Craft in Docker throws '/app/web/cpresources doesn’t exist or isn’t writable by PHP'

texts:
I'm trying to deploy a Dockerized Craft CMS website. The basic setup is as follows:

craft running in Docker
nginx running on the server, using proxy_pass to point to docker container

The setup itself seems to work, but Craft throws /app/web/cpresources doesn’t exist or isn’t writable by PHP when visiting the website (temporarily running dev mode on server to debug).
So far, to me this seems like a permissions issue. But I don't know how to properly solve it. Locally (MacBook Pro), this all works fine. It's on the server (Ubuntu 20.04) I suddenly encounter this issue.
docker-compose.yml
version: '3.6'

services:
  app:
    build:
      context: .
      dockerfile: ./.docker-config/php/Dockerfile
    container_name: app
    env_file: .env
    volumes:
      - ./.app-data/craft/web/cpresources:/app/web/cpresources
      - ./.app-data/craft/web/images:/app/web/images
    restart: unless-stopped

  nginx:
    build:
      context: .
      dockerfile: ./.docker-config/nginx/Dockerfile
    container_name: nginx
    ports:
      - 8000:80
    volumes:
      - ./.app-data/craft/web/cpresources:/app/web/cpresources
      - ./.app-data/craft/web/images:/app/web/images
    restart: unless-stopped

  database:
    image: postgres:12.4-alpine
    container_name: database
    env_file: .env
    volumes:
      - ./.app-data/database:/var/lib/postgresql/data
    restart: unless-stopped

  adminer:
    image: adminer:4.7.7-standalone
    container_name: adminer
    ports:
      - 8080:8080

Dockerfile (Craft)
FROM composer:2.0.4 as vendor
COPY ./craft/composer.json composer.json
COPY ./craft/composer.lock composer.lock
RUN composer install --ignore-platform-reqs --no-interaction --prefer-dist

FROM craftcms/php-fpm:7.4
COPY --chown=www-data:www-data --from=vendor /app/vendor/ /app/vendor/
COPY --chown=www-data:www-data ./craft/ .


texts: Setting the position of a Smart Map marker on the front end

texts:
I'm using Smart Map in a front end entry form and trying to set the position of a marker as the user enters their address.
I can get the lat/lon lookup working but I'm stumped with the marker itself.
Here's my JavaScript that's doing the lookup and filling in the lat/lon
$.post('/actions/smartMap/lookup', data, function(response) {
    if(response.status = 'OK'){
        // get lat/lng and populate hidden fields
        $('.js-address-lat').val(response.results[0].geometry.location.lat);
        $('.js-address-lng').val(response.results[0].geometry.location.lng);

        // update map (add marker)
        smartMap.map['smartmap-mapcanvas-1'].setOptions({styles: styles});

        var lat = parseFloat(response.results[0].geometry.location.lat);
        var lng = parseFloat(response.results[0].geometry.location.lng);
        var newLatLng = new google.maps.LatLng(lat, lng);

        smartMap.marker['smartmap-mapcanvas-1.{{ property.id }}.location'].setPosition(newLatLng)

        smartMap.refreshMap(smartmap-mapcanvas-1);

    } else {
        alert('No address could be found');
    }
});

The docs say to reference the marker as
smartMap.marker['<MAP ID>.<ELEMENT ID>.<FIELD HANDLE>']

With the <ELEMENT ID> being the ID of the marker's parent element. But what would be? Is that the ID of the entry? I'm trying that but it just seems to lock the browser up and the fields don't save.


texts: How can I retrieve channel data in json format?

texts:
I've played around with a few implementations but I still don't feel like either is right.

I first came across building the JSON itself. This would be in a file at "craft/templates/entries.json".

[
  {% for entry in craft.entries.section('news').find() %}
    {
      "title": "{{ entry.title | e('js') }}",
      "body": "{{ entry.body | e('js') }}"
    } {% if not loop.last %},{% endif %}
  {% endfor %}
]

This worked but I didn't feel right about writing my own JSON so I came up with this approach instead.

{% set results = [] %}
{% for entry in craft.entries.section('news').find() %}
{%
  set results = results | merge([{
    'title': entry.title,
    'body': entry.body
  }])
%}
{% endfor %}
{{ results | json_encode() | raw }}

This works, the JSON will definitely end up valid and as a bonus it'll be condensed but it's not very reusable and when I add fields I need to adjust it.

What approach should I take to make a reliable way to query data from Craft and return json?


texts: Is there a way to turn off a language in Craft Commerce?

texts:
I have a site that serves German content. Now we have an admin that wants to have the backend in English.

So I've added English in the locales. This works fine for standard Craft things.

But in Craft Commerce all of the products are now in two languages. Is there a way to turn off the language for Craft Commerce?

I've looked into product types, but you can't just turn off a language.

Problem is, that this admin is also the CEO of that shop.


texts: Query entries relatedTo multiple categories in controller

texts:
I have an AJAX GET call that should count all the products matching three different taxonomies.

Product families
Sectors of application
Liquids suitable for the product

so in the form the user could select pumps, agriculture, diesel and the controller called should count the products that matches all those criteria.

I get the solution in the templating engine:

{% set relationParams = ['and', id1, id2, id3 ] %}
{% set products = craft.entries.section('products').relatedTo(relationParams) %}

But something is not working as expected in the controller:

        $prodCriteria = craft()->elements->getCriteria(ElementType::Entry)->section('products');

        $prodCriteria->relatedTo = array(
            'and',
            'targetElement' => $catIds // Where $catIds is an array of ids
        );
        $products = $prodCriteria->count();

        $this->returnJson( $products );

It seems like relatedTo behave like an or operator.
Also, is it possible to make the relatedTo behave in a more complex way, like, I want to use or for product families and and for other taxonomies?


texts:
Is there a way in Twig to make this conditional shorter so I don't use "craft.request.getSegment(2)" twice?

{% if craft.request.getSegment(2) == "knowledge" or
craft.request.getSegment(2) == "search" %}


texts: content and fields won't show up on new single

texts: I just installed Craft, linked it to my database (localhost) and then created a new single "about" page. But when I go to edit the single, there are no fields. I haven't changed anything else! When I go to the slug it shows the right template, but there's no content to pull in, since I can't add it in with the dashboard. I've enabled Dev Mode and there are no error logging. Any ideas?


texts: Eager load commerce order data in custom ElementExporter for Users

texts:
I have a custom ElementExporter for users and I'd like to include commerce order data. The below code works, but it's a ton of queries. I don't have a ton of experience with SQL queries, how can this be optimized with eager loading?
public function export(ElementQueryInterface $query): array
{
    $results = [];

    /** @var ElementQuery $query */

    foreach ($query->each() as $user) {
        /** @var User $user */

        $orderTotal = '';
        $orderDate = '';
        $order = Order::find()
            ->user($user)
            ->hasPurchasables('41599')
            ->orderBy('dateOrdered desc')
            ->dateOrdered('>= 2020-09-01')
            ->isCompleted(true)
            ->one();

        if ($order) {
            $orderTotal = '$' . $order->totalPrice;
            $orderDate = $order->dateOrdered->format('m/d/Y h:iA T');
        }

        $results[] = [
            'Donation Amount' => $orderTotal ?? '',
            'Donation Date' => $orderDate ?? '',
        ];
    }

    return $results;
}


texts:
I created grouped category name projectCategory and assigned projects as the parent of design, 3d and art.

In project section (Channel) I have wrote {projectCategory.first().slug}/{slug}  and in categories (projectCategory) the top level is {slug} and nested categories {parent.uri}/{slug}.

Setup the field (projectCategory) so that I can assigned entry to selected category. So far

The result is not what I am hoping for at the moment sample.com/projects/mer-car-model is what generated. I was hoping that it should read sample.com/projects/3d/mer-car-model. I would appreciate some guidance how to achieve the result.


texts:
I am trying to code defensively and check whether a field exists before accessing it:

{% if e.someField is defined %} {{e.someField}} {% endif %}

And I get a CException

  Craft\EntryModel and its behaviors do not have a method or closure named "someField".

Because is defined is always returning true.

Any clue what's wrong?


texts: Craft is not installed yet with a REDIS error

texts:
Our website is on the latest version of Craft 3.4, using REDIS (redis_version: 4.0.9) for Sessions and Caching.
Today the website stopped working with the well-known "Craft is not installed yet".
storage/logs/web.log contains the following lines:
There was a problem fetching the info row: Redis error: MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error.

Redis command was: SET CV-PROD9350e89e77a3b08b9480b6f648d34509 a:2:{i:0;s:23:"5.7.33-0ubuntu0.18.04.1";i:1;N;} PX 3600000

2021-03-26 12:39:55 [-][-][e0mfa29m7jagmbfurqnbqitptr][error][yii\db\Exception] yii\db\Exception: Redis error: MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error.

Redis command was: SET CV-PROD9350e89e77a3b08b9480b6f648d34509 a:2:{i:0;s:23:"5.7.33-0ubuntu0.18.04.1";i:1;N;} PX 3600000 in /data/www/xxx/web/xxx.com/vendor/yiisoft/yii2-redis/src/Connection.php:821

Any ideas what is causing this?
Is there any Craft config I could set to avoid it?
Modifying the REDIS config is an option, but I would prefer solving this via Craft's config.