texts: Craft 3: Debug Toolbar is 404ing and won't display on multi-site setup

texts:
When I am logged in as an admin and I have both of these options enabled on the user preferences:

... the Yii debug toolbar still does not display and there is a 404 error that appears in console, stemming from a request to index.php:

Please note that I have a multi-site setup (main site and then two secondary sites), and there have been some other cases where other people have the same issue: Craft 3: how to show the Yii Debug Toolbar?
However, I have yet to see what exactly is done in order to properly fix this. Someone has noted to simply login into a secondary site in order to see the toolbar. I've logged into both of my secondary sites, as well as my main one, but the toolbar still fails to show up.
I've also tried to clear Control Panel caches to no avail. Help would be much appreciated. Thanks!


texts: Sort single entries by section with same query order

texts:
When querying multiple singles by section slugs, is it possible to maintain the order of the results as the query?  Currently the return result is sorted by the default postDate desc.

craft.entries.section(['section1', 'section2', 'section3'])

returns an array with the order
section1, section2, section3

Documentation doesn't seem to answer this question.
https://craftcms.com/docs/templating/craft.entries#order


texts:
I may be missing something really obvious in the docs - so sorry if I have - but is there a way to send both the user (sender) a notification email, and the admin a different notification email?

Something like what I want has been hinted at: Sprout Forms CC

I know I could set multiple email addresses in the notifications option: Sprout Form > Forms > My Form > Notifications (tab) > Email Recipients (field) but the issue I have is how can I dictate which template is used?

I'm happy to set/use the default options for the Admin email, if you could point me in the right direction for a custom user email option, that would be great.


texts: Single type for entry submission on error loses entry object

texts:
I have created a contact form inside a single entry type 'contact' for front end submissions.
This lets me display editing options for title and body and display the form.

When submitting the form, the entry object ( eg entry.title ) disappears and no title or body  content is shown - just the form with its corresponding errors.

So submitting it seems to lose the entry - is this because it is returning the saved entry model and not the single that it is on?


texts: How do I reference the settings of my plugin from a template?

texts:
This question and answer explains how to access a plugin's settings from elsewhere in the plugin's PHP code.

How would I access these settings from within a template? Or this impossible and I'd have to pass the values into the template when rendering it? ie, in a Controller action:

$settings = craft()->plugins->getPlugin('myPlugin')->getSettings();
$templateVars = array(
    'foo' => $settings->foo,
);
$this->renderTemplate('myPlugin/templateName', $templateVars);


texts: Freeform Checkbox Group Field only returns one value

texts:
I need a scenario where users can select multiple options within a checkbox group.  Unfortunately Freeform only returns the last value selected and ignores the rest?  I might be missing the point but I expected to see all (and only) the values selected represented in the submissions area?

Any ideas?

Thanks


texts: So I've created a web portal for a client so they could upload a file which triggers a Feed Me feed (on that file). I handle the upload and triggering of the feed with a custom Module. I trigger the feed using the php exec function and the feed's Direct Feed URL. I would love to show the user the log for the Feed's task while it's running, so they would know if any errors occur. Is there a way to do this?


texts: What would be the best way to track downloads by user?

texts: Is anybody familiar with a plugin (similar to EE's Link Vault) that tracks all downloads, by user?


texts: Getting image url error code: Impossible to access an attribute ("url") on a null variable

texts:
My site just suddenly broke down on a certain page with the following error code, (see screenshot).

It is occuring for every image on this page and really confusing me.

Any quick suggestions?


texts: Get email address from registration form

texts:
I have a user registration form setup to redirect to another template on submit. That template then includes the following:

{% set email = craft.app.request.getBodyParam('email') -%}
<p>Thank you for registering. An email has been sent to {{ email }}…

Why does getBodyParam('email') always return empty here? getBodyParams() also returns an empty array.


texts: Best way to delete submitted data in Sprout Forms?

texts:
There are a few hundred form entries and manually going into each one and deleting sounds like far too much work!

Guess i could delete each form (there are 5) which would delete each form submisson. Then recreate the form again. Any other ideas? Thanks.


texts:
I'm trying to set up a front end user profile that will allow the user to use the multi-select field. When I update from the CP, the changes are reflected on the front end, but this isn't working when trying to update from the front end form.

Is there anything I'm missing?

{% set languageOptionsIds = user.providerLanguages %}

<label for="providerLanguages">What languages do you work with?</label>
{% for option in currentUser.providerLanguages.options %}
    <input type="checkbox" id="providerLanguages" name="fields[providerLanguages][]"
    {% if option.selected in languageOptionsIds %}checked{% endif %} value="{{ option.selected }}">{{ option.label }}
    </input>
{% endfor %}


texts: Can Craft handle thousands of entries and high traffic?

texts: We are going to start an online magazine. Registered users will be able to submit new entries (articles, places, etc...). Can Craft handle thousands of entries and high traffic (Of course with required server)?


texts: Is there a way to choose the font family in rich text field? I want to have the option to choose from 2 or 3 font families in the rich text field. Is that possible in craft?


texts: Overwrite Matrix data programatically and save

texts:
I'm working on a translation plugin. Now I want to translate fields in a matrix and save it to the right site (language). This plugin is called in a after save event. It gets the value of the Dutch draft, translate it and save it in the right language.
For simple fields it works and saves correctly, but it fails saving matrix data.
$field = "companyRocks";
$matrixField = "companyRockTitle";
$customField = Craft::$app->getFields()->getFieldByHandle($field);
$existingMatrixQuery = $this->dutchDraft->getFieldValue($field);
$serializedMatrix = $customField->serializeValue($existingMatrixQuery, $this->dutchDraft);

foreach ($serializedMatrix as $key => $matrix) {
    $serializedMatrix[$key]["fields"][$matrixField] = $this->translationClient->translate('nl', $entry->locale, $serializedMatrix[$key]["fields"][$matrixField]);
}
$fieldValues = [];
$fieldValues[$field] = $serializedMatrix;

$entry->setFieldValues($fieldValues);
Craft::$app->elements->saveElement($entry);

This is what the front end looks like:

And this is the input of setFieldValues with the right translation ofcourse:
Array
(
[companyRocks] => Array
    (
        [845] => Array
            (
                [type] => companyRock
                [enabled] => 1
                [collapsed] =>
                [fields] => Array
                    (
                        [companyRockTitle] => car
                    )

            )

        [1088] => Array
            (
                [type] => companyRock
                [enabled] => 1
                [collapsed] =>
                [fields] => Array
                    (
                        [companyRockTitle] => bicycle
                    )

            )

    )

)

After saving it programatically it just saves the Dutch version. Even when I die the program after saving the first (English) entry it still shows the Dutch version, so it's not overwritten somewhere else in the program.


texts: Remote assets space issue storage/runtime/assets/sources

texts:
I was wondering if someone could help me with the following issue:

I'm saving assets on Amazon S3 and as per Craft's documentation Craft is keeping a copy of remote assets in storage/runtime/assets/sources folder. The issue is that this website has a lot of images and sources folder in storage is taking up a lot of space. It can go up to 5GB.

Is there a way I can tell Craft to not keep a copy of remote assets?

Many thanks


texts:
We have a website built in Craft 3.4.14 and we are moving it to a hosting company with CentOS 7, using Plesk Obsidian 18.0.5.

The hosting company has told us that they have upgraded Composer from version 1 to version 2. On my local machine I have been using version 1.10. However, I try to run Composer on the server and I get these issues: -

craftcms/plugin-installer 1.5.3 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.0.0] but it does not match your constraint.
craftcms/plugin-installer 1.5.4 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.0.0] but it does not match your constraint.
craftcms/cms 3.4.14 requires craftcms/plugin-installer ~1.5.3 -> satisfiable by craftcms/plugin-installer[1.5.4, 1.5.3].
Root composer.json requires craftcms/cms 3.4.14 -> satisfiable by craftcms/cms[3.4.14].

Is there a way around these issues so that we can get Craft CMS installed please?

Thank you for your time.


texts: Custom field type file upload error [Uploaded File Class]

texts:
I need to upload a file to my server via a custom field type and I'm trying it like this:

    public function prepValueFromPost($value)
{
    // Get file
    $file = \CUploadedFile::getInstanceByName('fields[handle]');

    // Determine folder
    $folder = 'folder/to/upload';

    // Ensure folder exists
    IOHelper::ensureFolderExists($folder);

    // Get filepath - save in storage folder
    $path = $folder . $file->getName();

    // Save file to Craft's temp folder for later use
    $file->saveAs($path);
}

public function getInputHtml($name, $value)
{
    return craft()->templates->render('_includes/forms/file', array(
        'name'  => $name,
        'value' => $value,
    ));
}

This sadly ends up in the following error:

Fatal error: Call to a member function getName() on a non-object in...

Does anyone have an idea how to solve this? My file input has the name "fields[handle]" but i also tried "handle" but nothing changes...


texts:
I'm trying to find a method of escaping characters in Craft's DateTime object.

This is the output I'm trying to achieve: 16th January 2016

This is what I've tried: {{ article.postDate.format('j\<\s\u\p\>S\<\/\s\u\p\> F Y') }}

This is the output: 16&lt;00000000p&gt;th<!--00000000p--> January 2016

I can achieve the output by appending output together but there has to be a better way of achieving this than the following:

{{ article.postDate.format('j') }}<sup>{{ article.postDate.format('S') }}</sup> {{ article.postDate.format(' F Y') }}

Any pointers to documentation would be appreciated.


texts: Change naming of sections in Craft Commerce CMS

texts: Is it possible to change the name of the of 'Products' to 'Projects' & Variants to 'Pledges'? I would like to use the Commerce CMS as a base to start from but need to be able to change certain naming of sections. Where can I do this?


texts:
I'm a relative newbie to Craft CMS / Solspace Freeform. I'm trying to implement a form which will capture some basic details and send to an email address.

I've done the setup correctly (from what I can see) however when I go into email notifications I can only see database entry templates and no email notification templates.

When I test my form it submits the data to the submission page on Craft but no email is ever sent.

Could anyone point me in the right direction?

There is a contact form and related template setup by someone prior to me on the website which I know emails to a specified email address, but I can't seem to get mine working.

Thanks.


texts: createCommand sql query not working in plugin

texts:
Hi I have a plugin which I am running an sql statement from.

$users = craft()->db->createCommand("SELECT craft_users.id as userId, craft_users.firstName, craft_users.lastName, craft_users.email FROM craft_users INNER JOIN craft_content on craft_users.id = craft_content.elementId WHERE craft_content.field_interests LIKE '%\"8948\"%'");

The query is not returning the expected results from the createCommand function in fact it returns an empty array. But if I run it directly in the database it works perfectly and returns the entries.

I also tried building this with the query builder but it was throwing errors and not finding the user table.


texts: I am very new to Craft CMS and just testing out the CMS. In our old system we had 2 levels of virtual folders and I need to keep that structure. I don't see anything that would correspond to that in Craft. Is there anything that would let me create 2 levels of folders?


texts: Query entries by custom date field (for a particular year)

texts:
So I'm trying to get all entries that have a particular year assigned to a custom date field. (Could be any day/month in that year).

The custom field is startDate and my attempt at a query - which doesn't work - is below...

PS. year is a 4 digit variable set via the last segment of the url and pulled into the template as a variable, and giving you 2018, 2019 or whatever...

{% set query = {
  section: 'programme',
  isOngoing: 0
} %}
{% set programmeEntries = craft.entries(query).search('startDate:' ~ year|date('Y-m-d')) %}

PS. I think it's more like this but I can't get the syntax right...

{% set query = {
  section: 'programme',
  isOngoing: 0,
  startDate: ( ['and', '>=' ~ (year~'-01-01')|date('Y')|atom, '<=' ~ (year~'-01-01')|date('Y')|date_modify('+12 months')|atom])
} %}


texts: Compare Value to Category Title In Template

texts:
I'm new to Craft and am trying to set up a condition that will compare the value of a category (entry.position).  However, I get this error message:

Object of class Craft\ElementCriteriaModel could not be converted to string

I'm not really sure how to do a textual comparison.  The 'position' field is, in my case, a category.  How would a comparison be achieved?

I've tried this:

{% set entry_pos = entry.position %}
{#   {%  craft.categories.slug('position') %} #}
{{ entry_pos }}

{% if entry.position != 'staff' %}
    {% if entry.UBFUserName != '' %}
        {% set name_var = entry.UBFUserName %}
            {{ craft.aitest.AiTestVariable(name_var) }}
        {% else %}
    {% endif %}
{% endif %}


texts: Image transforms on remote server are broken by `cpresources/transforms` url

texts:
My local image transforms successfully load in the FE but they do not load remotely.

This is the local url where images load successfully /uploads/case-studies/deployment-image/_caseStudyDeploymentImage/image.jpg

This is the remote url where images are broken https://www.mysite.com/cpresources/transforms/8?x=IXLDGt3eW

This has happened before but i can’t remember why or how i fixed. i have cleared asset indexes in CP Settings.


texts:
When you click in search form and press 'Enter' or 'Submit' button, it returns all entries, that exist in database.

How could I display some message rather than all entries?


texts: How can I fire a controller action for a particular route or entry?

texts:
So I have an entry that has some content displayed in a template.

However ahead of displaying that entry, I want a plugin's action to fire, which pulls some data in from a third party API that will display along with the entry content in the template.

The data from the plugin would need to be available in the template that gets loaded.

What's the best approach to do this?

Here's my routes.php file:

return array(

    'book' => array(
        'action' => 'micros/availability/search'
    )

);

And my plugin:

<?php
namespace Craft;

class Micros_AvailabilityController extends BaseController
{

    protected $allowAnonymous = true;

    public function actionSearch()
    {
        Craft::dd('Micros_AvailabilityController->actionSearch()');
    }
}

I have an Entry with a slug of 'book' and that loads a template from the templates directory, so what I'm seeing right now is that template, and I don't get the action method running at all.

What I want to do is do something in my action and attach the data to the request and return to whatever template the entry is using.


texts: Automatically replace strings in different language

texts: We have sites for Germany and Switzerland that are pretty much identical but would like to cater to the spelling differences in Switzerland (namely replacing "ß" with "ss"). Is there any way to run the whole content of the German sites through a filter replacing characters where needed for the Swiss site? Since most content identical it would save us from having to update the same content twice. The Twig replace filter could do that but then I would have to set the filter for each field if I am not mistaken.


texts: Sort / Order Entries on select or button click

texts:
I have a page on my website were I display alot of entries. Now I want those entries to be sorted by Date, Title etc. I know how to change that hard coded but I want to make it dynamic with a <select>. I guess I need to use Ajax for this but after a long search I still cant figure it out.

The Select

        <select>
            <option value="{% set order = "postDate asc" %}">New - Old</option>
            <option value="{% set order = "postDate desc" %}">Old - New</option>
            <option value="{% set order = "title asc" %}">A-Z</option>
            <option value="{% set order = "title desc" %}">Z-A</option>
        </select>

The loop

        {% set counter = 0 %}
        {% for entry in craft.entries.section('tips').order('{{ order }}') %}
            {% set counter = counter + 1 %}
            {% include 'includes/tip-blocks' %}
        {% endfor %}

To make the question short.

Sort entries dynamicly through a select form. Prefer not to reload the page but, it's oke if it does.


texts:
I'm getting close to finishing my first project on Craft CMS but I have one problem.
I'm using number fields to rate items in my entries. It looks like this:

I will have around 6-7 fields and I need to get the average rating of them to display in the front end.
{% set ratingAverage = entry.dizainas + entry.ekranas + entry.veikimas %}

{% set ratingsSum = ratingAverage / 3 %}

<strong>{{ratingsSum|number(decimals=1)}}</strong>

In fact, some of those fields might be left empty as well so it's needed to skip them.
Can someone help me out with this?


texts: Is it possible to add an attachment to a Craft Commerce order status email?

texts:
I'm trying to figure out a way to attach an asset file to a Craft Commerce order status email when a user purchases a product- the user would be purchasing the file and I'd like to attach it to the order status email that's sent upon completion of purchase.

I see that the Contact Form plugin has a similar functionality:

https://github.com/pixelandtonic/ContactForm/blob/master/contactform/services/ContactFormService.php#L54

Is it possible to do something similar in Craft Commerce?


texts: Entry FieldType - Get the EntryModel of the entry chosen in the field?

texts:
So I have some entries and one of the fields is for a "hotline". The hotlines are all entries. The CMS part works, I can click the field and choose an entry from the hotlines channel, however this is where I'm stuck.

In my plugin code I cannot seem to figure out a way to actually get the hotline that was chosen.

I have a $center variable which is an EntryModel of the entry that has the field for "hotlines" attached to it, with the value set (according to the admin).

$center->hotline and $center->getFieldValue('hotline') just return an ElementCriteriaModel and when I inspect that object inside xdebug there is nothing there that would be usable in getting the actual hotline that's selected. No ID. No object. No nothing. Just information about the field it self, not the value.

What the heck am I doing wrong here? This is so "unintuitive" compared to the rest of craft!


texts: Cannot add new field when Project Config enabled

texts:
I'm working locally and am unable to create or edit fields if I have project config enabled in general.php

'*' => [
  'useProjectConfigFile' => true,
],

If I change that to false I can add fields, but as soon as I change it back to true, the fields disappear from the control panel.


texts:
I'm experiencing a problem where none of the plugins (2 captchas, and a random bookworm plugin) are showing up in my admin panel.

Folders are lowercase.

I've also checked permissions; folders are at 755. The corresponding file is at 644.

I have the Pixel & Tonic Contact Form plus the RetconHTML plugins currently in there, so I know I've successfully uploaded plugins before. Just not sure what's going on.

Thoughts?

-edit-

The two plugins I'm currently having problems with are bookworm and recaptcha, not anything I've specifically developed.

Here's a screenshot of my plugins directory:


texts: Is there a way to access another database outside of the one Craft uses for its content? I need to able to access data fields from an external source for a project I'm working on.


texts: Search form - Passing only field params that are not empty or selected

texts:
Is it possible to have a search form pass (into the search query) the field params of only fields that have been populated/selected? For example, if the following form is submitted, both q and color params are passed in the receiving template to which the form submits.
<form action="{{ url('search/results') }}">
    <input type="search" name="q">
    <select name="color">
        <option value="">Select a Color</option>
        <option value="black">Black</option>
        <option value="white">White</option>
    </select>
    <input type="submit" value="Go">
</form>

Output URL: http://mydomain.com/people/results?q=&color=
I have a search form that includes a lot of fields, so I want to only pass the params that are not empty or have been selected. This way, the URL that's passed is cleaner and less monstrous.
So in the example above, if the color dropdown isn't selected, the output URL would be http://mydomain.com/people/results?q=somequerystring


texts:
I am grabbing a date range from a URL query string like so:

https://website.com/qa/search-feedback-results?datestart=2019-01-01&dateend=2019-02-26

I can't figure out how to include posts that were submitted on the end date that is in the range. In the above example, any posts dated 2019-02-26 are not showing up in my results.

Here's my code:

{% set vDatestart = craft.app.request.getParam('datestart')|date('Y-m-d') %}
{% set vDateend = craft.app.request.getParam('dateend')|date('Y-m-d') %}
{% set vParams = vParams|merge({ postDate: ['and', '>= ' ~ vDatestart, '<= ' ~ vDateend] }) %}


texts: Call to Craft Users Login Function from Plugin

texts:
I am migrating a 15,000+ users from a site's old CMS (WP), and have them set to Pending. All of their user information will be created and on Craft CMS, except their passwords will not be set, as migrating that is too complicated (for what I can tell.) So, the process I have in mind for previous users to login is:

User enters Username/Email & PW, submits login form.
Form sends data to custom Custom Plugin Controller, and follows logic:

If user status==active, simply send form data to Craft's users/login and proceed as usual.
If user status==pending:

Check if username/email exists in previous users list.

If it does not, simply send form data to Craft's users/login and proceed as usual.
If it does exist, it sends the Activation Email and redirects to special URL stating "You've been sent an email to re-activate your account on this new website."

Is this possible to do? It would be fairly straight forward to write, except I am unsure if there is a way to communicate with Craft's users/login via a plugin. Is it something like craft()->users->login( $userNameOrEmail, $userPassword )?

I'm aware I could also just send out batch email activation links to the migrated users, but I'd much prefer this method, in case they miss those e-mails and try logging in at a future date. Alternatively I could have a "Are you a user of the old site? Click here to re-activate your account." Link on the login page, but again users may not notice it and think they cant login anymore.

Any help would be hugely appreciated! Thanks.


texts: Entries form in control panel won't display if I have a Matrix field enabled

texts:
I'm new to Craft, and have a local installation of version 2.6.2789

I have created a section with its own field layout. Everytime I enable a matrix field in the field layout, the section entry form won't display anything.

Attached is the screenshot of the entry form itself.

Not sure what I'm doing wrong.


texts: Why are my entries disappearing when {% if category | length %} is added?

texts:
Editing an index page that displays all entries within a structure.

Everything displays fine.

I add a category to a few entries and add {% if category | length %}and everything disappears as if no entries had a category.

I get no twig errors, so I presume my code is okay.

Here it is, just in case:

          {% set entries = craft.entries.section('fellows').relatedTo(category) %}
      {% if category | length %}
        {% if entries | length %}
          {% for entry in entries %}
            {% for matrixBlock in entry.fellowsEntry %}
              {% if matrixBlock.type == 'entryContent' %}

                        {% for image in matrixBlock.fellowImage %}

                         {% endfor %}

{{ entry.title }}

{{ matrixBlock.organization }}

                        {{ category }}

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


texts: Prevent Craft URLs containing # from redirecting

texts:
I have a Structure setup where I'd like each child to link to an anchor within the parent page (see the attached image).

But when I use <a href="{{ subEntry.url }}"> and click on the link, it redirects to the parent URL without the # anchor.

e.g. http://localhost:3000/services/web-interactive-design#website-design redirects to http://localhost:3000/services/website-design

How can I prevent this from happening?


texts:
I was wondering if it was possible to allow a customer to apply a coupon code using a URL or URL params in Commerce 2. I haven’t been able to find any questions on stack exchange or on the web, but the scenario I’m trying to support is:

Customer receives an email with a coupon code (includes a coupon code image that links to the storefront)
Customer clicks a link which takes them to the store and automatically applies the coupon with a toast confirmation (e.g. store.com?coupon=somecouponcode)
Customer adds purchasables to cart and when they go to the cart page, the coupon is already applied to cart lineitems without requiring them to manually input it themselves


texts: How to do multi-day events in Solspace Calendar?

texts:
If I'm adding events for course that is run Wed 8-5, Thurs 8-5, and Fri 8-12, how would I do that? It's not technically a recurring event, I don't think, but at the same time, it's not individual instances either. This event (or course) runs multiple times a year, to complicate things a bit more.

Has anyone done anything similar?


texts: can't login after move site to local - empty response

texts:
After migrating a site to local i can't login into the backend-part /admin/login.
There is an error message in the browsers console log

VM1974:1 POST http://great-site.localhost/index.php?p=admin/actions/users/login net::ERR_EMPTY_RESPONSE

I debugged into the backend until the return $this->asJson($return); line 1671 in UserController (vendor/craftcms/cms/src/controllers/UsersController.php).
But somehow it seems to not return anything as the browser console says.
I am on Craft Version 3.3.6
PHP Version 7.3.18
Questions upfront
Could it be that i am running on http instead https now?
Could it be that i am not creating a session correctly?


texts: Does composer update make changes to the SQL database

texts:
When creating plugins on my local I need to run composer update to make sure everything is in sync. In order to make sure the client has the same vendor and plugin folders, I then upload them to the server.

I just want make sure that when running composer update that Craft does not make changes to the database. If so, I need to make sure I also send the latest database to prod as well.

We've made a cli tool to easily sync environments, and I would like to add a command that takes care of this edge case as well.


texts: MultiAdd - Add a related product by checkbox

texts:
Using the MultiAdd plugin, I'm trying to add a related product using a simple checkbox. It's an add on to the existing product.

Here's a screenshot of what it looks like on the page…

I want the related product to:

be added when the checkbox is ticked and vice versa when not ticked
have the same quantity as the parent product

Here's is the relevant code inside my variant loop:

<form method="POST" id="addToCart">
<input type="hidden" name="action" value="multiAdd/multiAdd">
<input type="hidden" name="redirect" value="shop/cart">
{{ getCsrfInput() }}

{# Code For Related Product #}
{% if relatedProduct | length %}

        {% for product in relatedProduct %}
            {% set variant = product.defaultVariant %}

                <input type="checkbox" name="items[addon][purchasableId]" value="{{ variant.id }}" checked="checked">
                {{ variant.title }}
                +{{ variant.salePrice | commerceCurrency(cart.currency) }}
                {% if variant.onSale %} {{ variant.price | commerceCurrency(cart.currency) }}{% endif %}

            <input type="hidden" name="items[addon][qty]" value="1">
        {% endfor %}

{% endif %}

{# Code For Product #}
<input type="hidden" name="items[product][purchasableId]" value="{{ purchasable.id }}">
<select id="quantity-standard" name="items[product][qty]" class="quantity">
    {% for i in 1..50 %}
        <option value="{{ i }}"{% if loop.first %} selected{% endif %}>{{ i }}</option>
    {% endfor %}
</select>
<input type="submit" class="buy-now" value="{{ "Add to cart"|t }}">

The challenges I'm facing are…

I don't know how to set the related product's quantity to zero when the checkbox isn't checked
I don't know how to set the related product's quantity to match the parent product when the related product is checked

Any help would be appreciated!


texts: Freeform submission only works if 'devMode' => true

texts:
I have a locally running form via Solspace's Freeform plugin (Craft2) which perfectly runs on my local setup, but fails silently without any logs or messages on my live-setup.

The form is submitting and saving entries only if dev-mode is true?

Update 1:
.dev (with dev-mode true) --> works
.com (with dev-mode true) --> works
.dev (with dev-mode false) --> doesnt work
.com (with dev-mode false) --> doesnt work

Update 2:
After clicking on submit the document transforms to POST but the URL is not getting changed nor does one get redirected to set returnUrl.

Update 3:
Without changing anything I got it to accept data three times. Not reproduceable.

Update 4
Because I've read a lot about interfering of .htaccess-rewrites & post method, here is my current .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^111\.222\.333\.44$
RewriteRule ^(.*)$ https://mydomain.com/$1 [L,R=301]
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC]
RewriteRule ^(.*)$ https://mydomain/$1 [R=301,L]
</IfModule>

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


texts: Register custom REST routes while building a plugin for Craft 3

texts:
I am building a custom plugin for Craft and I am hitting some REST APIs in my backend service to fetch some data using Ajax calls in JS. What I would like to do when the AJAX calls complete and come back with data, is to store some data in Craft. I know I can use projectConfig to store and retrieve plugin based data and settings but how to call those Craft functions through my JS files. The way I figured is to call it using REST routes that I can define via my plugin.

But I am not sure how to register routes using my plugin and how to setup controllers for the same.

Main plugin file:

Event::on(UrlManager::class, UrlManager::EVENT_REGISTER_CP_URL_RULES, function(RegisterUrlRulesEvent $event) {
            $event->rules['poptin/signup'] = 'poptin/default/signup';
        });

DefaultController.php

<?php
/**
 * poptin plugin for Craft CMS 3.x
 *
 * Create advanced website popups and forms, and improve your website's conversion rate within a few minutes.
 *
 * @link      poptin.com
 * @copyright Copyright (c) 2020 Poptin
 */

namespace poptin\poptin\controllers;

use poptin\poptin\Poptin;

use Craft;
use craft\web\Controller;

/**
 * Default Controller
 *
 * Generally speaking, controllers are the middlemen between the front end of
 * the CP/website and your plugin’s services. They contain action methods which
 * handle individual tasks.
 *
 * A common pattern used throughout Craft involves a controller action gathering
 * post data, saving it on a model, passing the model off to a service, and then
 * responding to the request appropriately depending on the service method’s response.
 *
 * Action methods begin with the prefix “action”, followed by a description of what
 * the method does (for example, actionSaveIngredient()).
 *
 * https://craftcms.com/docs/plugins/controllers
 *
 * @author    Poptin
 * @package   Poptin
 * @since     1.0.0
 */
class DefaultController extends Controller
{

    // Protected Properties
    // =========================================================================

    /**
     * @var    bool|array Allows anonymous access to this controller's actions.
     *         The actions must be in 'kebab-case'
     * @access protected
     */
    protected $allowAnonymous = ['index', 'signup'];

    // Public Methods
    // =========================================================================

    /**
     * Handle a request going to our plugin's index action URL,
     * e.g.: actions/poptin/default
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $result = 'Welcome to the DefaultController actionIndex() method';

        return $result;
    }

    /**
     * Handle a request going to our plugin's actionDoSomething URL,
     * e.g.: actions/poptin/default/do-something
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $result = 'Welcome to the DefaultController actionSignup() method';

        return $result;
    }
}

I see this error:


texts:
I'm trying to output the alphabet where certain letters are enabled/clickable based on whether any entries from a specific section start with that letter. Here's the UI:

Getting the A-Z is easy enough:
{% set letterArray = 'A'..'Z' %}

And I'm able to get the entries by first letter:
{% set entries = craft.entries.section('myEntries').orderBy('title asc').all() %}
{% set entriesByGroup = entries|group('title[:1]') %}
{% for firstLetter, entriesInGroup in entriesByGroup %}
    ...
{% endfor %}

I just can't figure out how to properly merge them so I can set a class or whatever on the letters that have at least an entry.


texts: How to loop through category group and identify those related to entry

texts:
Looping through a category group to show links to all the categories. This is an entry page and I want to highlight any categories assigned to the entry. How do I do that? I've tried this so far:

{% set cats = craft.categories.group('events').find() %}
{% for cat in cats %}
    {{ cat.title }}
{% endfor %}


texts: How to add a custom panel to the debug bar?

texts:
I'm working on porting a Yii2 component to Craft CMS as a plugin.
This Yii2 component provides a debug bar custom panel that I'd like to enable
in Craft CMS too.

In classic Yii2 applications, this is done by adding an entry to the
modules.debug.panels configuration directive:

'bootstrap' => ['debug'],
'modules' => [
    'debug' => [
        'class' => 'yii\\debug\\Module',
        'panels' => [
            'elasticsearch' => [
                'class' => 'my\\namespace\\DebugPanel',
            ],
        ],
    ],
],

Unfortunately, Craft 3 seems to hardcode this configuration in the
craft\web\Application::debugBootstrap() method.

How to add a custom panel to the debugbar in Craft 3?


texts: Display entries that belong to a category

texts:
I have a page that should show entries within a category, and then entries within children of that category. Basically, I need a way to loop through entries that have a level 1 category but not a level 2 category.

To give an example, suppose I've got some categories set up like this:

1.

— 1.1.

—— 1.1.1.

— 1.2.

2.

There's also one entry related to each category. I'd then use code like this:

{# Reference the category #}
{% set cat = craft.categories.title('1.').first() %}

{# Find related entries #}
{% set entries = craft.entries.section('mySection').relatedTo(cat).find() %}

{# Print them out #}
{% for entry in entries %}
    <p>{{ entry.title }}</p>
{% endfor %}

This would output:

1.

1.1.

1.1.1.

1.2.

How can I find entries which are directly related to the category “1.”?


texts:
Is there a way to hide a section from the Entries tab based on user permissions? Whether it means creating a user permission in a plugin, or hiding the section selection tab from Entries altogether.

I have a channel that users with a certain permission can create entries in using a front-end form. Once created, I don't want the user to see the entry in the CP or to have the ability to edit it.

I'd like to still allow them to see other entries in the "All entries" tab, so my original plan to hide these sections through CPCSS doesn't work. Any other ideas?


texts: URLs other than index cause 500 internal server error

texts:
I installed craft according to the documentation but when I tried to access example.com/admin I get following error

  Request exceeded the limit of 10 internal redirects due to probable
  configuration error. Use 'LimitInternalRecursion' to increase the
  limit if necessary. Use 'LogLevel debug' to get a backtrace., referer:
  http://example.com/

Every subpage like example.com/about has the same behavior. Only example.com works


texts:
I have a overview page that combines with two sections (documentation and galleries). Those two sections are attached to a parent Event. So you can select in the event entry a gallery or a documentation entry.

Question: How can i display those in order of the event's entry event day?

{% set entryGalleryIds         = craft.entries.section('gallery').ids() %}
{% set entryDocumentationIds   = craft.entries.section('documentation').ids() %}

{% set allEntryIds = entryGalleryIds|merge(entryDocumentationIds) %}

{% set allEntries = craft.entries.id(allEntryIds)|batch(3) %}

...

So i'm looking like something as:

{% set allEntries = craft.entries.id(allEntryIds).orderBy('events.eventDate desc')|batch(3) %}

Note: When i first query all the projects and then query the related galleries the sorting is gone, because of my id(allEntryIds) filter.


texts: Craft 3 installation issue on account creation

texts:
I try to install Craft 3 but I encounter an issue at the very beginning.
I uploaded the CMS via FTP and completed manually the .env file. When I try to run the installation, I get stuck at the account creation (the second step…) I want to create my account but the next button is doing nothing.
I get an error 400 "Bad Request // Unable to verify your data submission." When I send the form to create the admin account (POST to http://mywebsite.com/web/index.php?p=admin/actions/install/validate-account).

The server meet the requirements of Craft CMS (runned the server check and was ok). The DB connection is fine.

I tried to delete and reupload all the CMS but nothing changed.

Therefore, I'm unable to install Craft :| I saw some topics of the same issue but they're all unanswered.

Thanks a lot !

Here are the corresponding logs :

            2018-04-13 06:05:42 [2a02:a03f:3c1f:a00:6826:543f:275d:d8d5][-][-][error][yii\web\HttpException:400] yii\web\BadRequestHttpException: Unable to verify your data submission. in /home/MyWebsite/www/vendor/yiisoft/yii2/web/Controller.php:166
            Stack trace:
            #0 /home/MyWebsite/www/vendor/craftcms/cms/src/web/Controller.php(53): yii\web\Controller->beforeAction(Object(yii\base\InlineAction))
            #1 /home/MyWebsite/www/vendor/yiisoft/yii2/base/Controller.php(155): craft\web\Controller->beforeAction(Object(yii\base\InlineAction))
            #2 /home/MyWebsite/www/vendor/craftcms/cms/src/web/Controller.php(74): yii\base\Controller->runAction('validate-accoun...', Array)
            #3 /home/MyWebsite/www/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('validate-accoun...', Array)
            #4 /home/MyWebsite/www/vendor/craftcms/cms/src/web/Application.php(238): yii\base\Module->runAction('install/validat...', Array)
            #5 /home/MyWebsite/www/vendor/craftcms/cms/src/web/Application.php(446): craft\web\Application->runAction('install/validat...', Array)
            #6 /home/MyWebsite/www/vendor/craftcms/cms/src/web/Application.php(410): craft\web\Application->_processActionRequest(Object(craft\web\Request))
            #7 /home/MyWebsite/www/vendor/craftcms/cms/src/web/Application.php(147): craft\web\Application->_processInstallRequest(Object(craft\web\Request))
            #8 /home/MyWebsite/www/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
            #9 /home/MyWebsite/www/web/index.php(21): yii\base\Application->run()
            #10 {main}


texts:
Specifically, I'm looking at https://github.com/yiiext/shopping-cart-component. Can Yii extensions be made to work with Craft (or work out of the box)?

I'm unfamiliar with both, so I'm having a hard time approaching adding a shopping cart to this project, and I think rolling my own would turn out to be a mistake


texts: How do I get the siteName in a module (Craft 3)

texts:
In templates I can do something like {{siteName}}. But how do I retrieve this in a module?
I've tried:
Craft::$app->config->siteName
I can grab my custom globals via Craft::$app->globals, but the class reference doesn't say anything about the defaults like siteName


texts: How can I let JS UI building to field type plugin?

texts:
I want to use like owl carousel JS UI in front.

Here's carousel a link!

It has some option can setting.

I want to create a own fields type in admin, can setting this option and show this UI in front view.


texts: Cannot see local or s3 image asset source

texts: I have the correct image asset source for S3 and also a local folder. Neither folder contents show (they were previously) and I see an "unknown error occurred" popup. I've tried turning off image transforms, increasing my PHP memory limit and simplifying my templates but I haven't had any luck


texts: Craft install via composer: install to public_html?

texts:
When I do composer create-project craftcms/craft, it will create a web folder. My webroot is called public_html though. Can I change this somehow, or should I make a symlink?

Or simply don't use composer to install in that case?


texts: A server error occurred on drag and drop of entries

texts:
I am getting 'A server error occurred' at the top of the screen when trying to drag and drop entries in a structure. It happens only on my live site, local site works fine.
I have tried to change the live site to dev mode, doesn't help either.
The dragging does work but it doesn't save the new position.
Craft is updated to the latest version.
Did anyone had such an error?


texts: Have a custom plugin do something on every page load?

texts:
For an upcoming site build, I'm going to need to capture information on every page load for a number of sections. These will be pages based on standard entries, so I'd prefer to use traditional routing (so not handled through a custom controller). There will probably be three different sections that will each have the same information captured when the page is loaded – basically just a list of categories so we can track the most popular type of content and display it as a dashboard widget.

At first I assumed I could do this with an event, but it doesn't look like there are any events for a page being loaded. I'm currently thinking that I use JavaScript to fire an AJAX request to a plugin and send the data along. This will work, but generate extra page loads. I'm thinking it'd be more efficient if I could keep everything server side.

Is there some way to do this that I'm not seeing?


texts:
Can someone tell me how to do an image transform on a reference tag? I've tried

{% set images %}

{% endset %}

{{ images|parseRefs|raw }}

But this just gives back the source urls and not the crops.

Regards


texts: Attach Custom Information to Commerce Order Model

texts:
I have shipping methods that will require additional information from the user. For example, a local delivery shipping method which requires the user to include a timeframe for delivery (say, Thursday @ 3pm.)
I thought I'd go about it doing something like this:

On select shipping page during checkout, user selects the delivery date/time (based on what is available.)
User selects date, then submits form.
That date is attached somewhere to the order model.
The shipping method rules will validate the chosen date.
Include this additional information (selected delivery date) in saved order on checkout completion.

Is there a way to do this? Basically, I need to attach additional information for this shipping method (and another similar one.) I've looked through the order model docs but can't find a field I could add custom data to.


texts: Can you prevent upscaling when using Craft's image transforms?

texts:
With Craft's image transforms used to resize images or generate thumbnails, can you prevent images from being upscaled? There's often cases where it makes no sense to increase the dimensions of an image.

It would be great if there was a setting for this, but I can't find one documented.

Otherwise, is the solution to fetch the image size in Twig and then conditionally apply the image transform?


texts: Craft CMS combining element-api and Simple Map plugin

texts:
I've been using element-api for simple lazy-loading of things like blog posts, etc and now want to create a simple 'Postcode lookup' by utilising a custom filter (provided by the Simple Map plugin).

Simple Map provides a custom field that uses the Google Maps API for address data and geolocation.

My question is this: How would I call the custom Simple Map filter using the 'criteria' settings in element-api so that I can pass through a postcode (via a javascript call to the api/customer-search.json?postcode=M25ND) and return results based on the custom field filter?

I'm using Craft 3:

"require": {
    "php": ">=7.0.0",
    "craftcms/cms": "^3.0.0-RC1",
    "vlucas/phpdotenv": "^2.4.0",
    "roave/security-advisories": "dev-master",
    "craftcms/redactor": "1.0.0.1",
    "craftcms/element-api": "^2.5",
    "ether/simplemap": "^3.1"
},

element-api
https://github.com/craftcms/element-api

simple map https://github.com/ethercreative/simplemap

The below will return entries that are within 100 miles of the location provided:

{% set entries = craft.entries.map({
    location: 'M2 5ND',
    country: 'GB',
    radius: 100,
    unit: 'mi'
}).orderBy('distance').all() %}

.. and the simple look up in my element-api.php file currently returns all 'customer' entries:

<?php

namespace Craft;

use craft\elements\Entry;

// https://github.com/ethercreative/simplemap
// https://github.com/craftcms/element-api

return [
    'defaults' => [
        'elementType' => Entry::class,
        'elementsPerPage' => 9,
        'pageParam' => 'pg',
        'resourceKey' => 'entries',
        'transformer' => function(Entry $entry) {
            return [
                'id' => $entry->id,
                'title' => $entry->title,
                'url' => $entry->url,
                'map' => $entry->map,
            ];
        },
    ],
    'endpoints' => [
        'api/customer-search.json' => [
            'criteria' => [
                'section' => 'customers',
                'type' => 'customer',
                // how to include map({}) filtering of results?
            ],
        ],
    ]
];

What I'm struggling to do is combine the two. As far as I can tell; element-api criteria only works with the parameters listed here: https://craftcms.com/docs/templating/craft.entries

Thanks in advance for any direction you can provide.


texts: 'Could not find your craft/ folder' error despite following installation instructions

texts:
Thanks in advance for any help - I'm starting to feel like a fool for coming up against errors so often. But here goes.

I have confirmed with my hosting provider that Craft CMS is compatible.

I have put /craft/ folder and the contents of the /public/ folder next to each other in the htdocs directory on my hosting server.

I've updated the location of the /craft/ folder in index.php (to $craftPath = './craft';)

When I navigate to mysite.com/admin I get Could not find your craft/ folder. Please ensure that $craftPath is set correctly in /var/www/virtual/mysite/htdocs/index.php

I've checked that the root folder is performing correctly - I can successfuly navigate to an image at mysite.com/pic.jpg.


texts: Why is craft adding a rel attribute with inline styles in my textarea?

texts:
It looks like redactor is adding a rel attribute to images as they are added to content via the RTE. Removing the rel attribute and then switching views adds it back in again.

How can I remove the rel attribute as it's affecting validation: https://validator.w3.org/nu/?doc=http%3A%2F%2Fgrowthwise.com.au%2Fnews%2F2015%2Fgetting-organised-for-tax-sucks-is-there-an-easier-way


texts: What is the significance of craft.app.request.segments|last == _self

texts:
While reading this blog article about RSS templating, I came across the following twig code

if craft.app.request.segments|last == _self

I understand that the above command, in general, yields URL components as an array. But I don't understand under what scenario is the above condition true. What does _self mean in this context?


texts:
This is a fairly generalized question, maybe I completely missed where to learn about this, but I've always been curious about it as it'd help me be a little more aware of what would and would not be good practice in plugin development.

I often read the first user request is slowest to Craft Sites point mentioned in articles/posts, what exactly is that referring to?

With each page request are all plugins and their files opened and loaded up? Or are these loaded and stored somewhere for X period of time, decreasing loading time per request?

Some examples of plugin scenarios/questions

1:

I have a fairly decent-sized loop in two plugins via public function registerSiteRoutes() {} that generate 200-1000+ custom routes, as those URL's will not have any content from Craft's entries (and thus don't have URL's,) or are completely dynamic (for forum topics with unpredictable topic urls.)

Is this loop that creates these URL's running every single time a page is requested? Is this bad practice?

2:

I can have some plugin services load large files of data in __construct(), or as var $data; for use in specific scenarios. Under the assumption that these service files are only loaded when a plugin calls to it, it wouldn't be slowing requests down that don't use the data because only the pages calling for them would load the data, such as through craft()->myPluginName_serviceName->getVarWithLotsOfData; requests.

Or do these files get loaded up regardless of being called, and therefore should be re-written into functions so that they don't load the data unless asked?

3:

Plugin count -- does having many small, niche plugins affect load speed versus less but larger plugins that cover more functionality? Is plugin count something that needs to be carefully considered, a common caution when working with a plugin-based CMS like Wordpress?

--

Basically, I guess the question is, I would love to be able to read a detailed explanation of the scheme/process in how plugins and their respective plugin file, config, services, controllers, templates, variables etc are loaded, and if there is a guideline on what is and isn't good practice when designing the flow of plugins for optimization?

If there is documentation that I missed that greatly covers and explains all of this, feel free to link it and put me in a corner for shame. D:

Thanks,


texts: I have a table type field that I need to access to rows individually

texts: I'm new using Craft, I have a table type field display on one of my template but I need to display row 2 and 7 in different places of the page how can display only those two rows.


texts: Conditional to compare segment_1 in the URL with the URI of a specified entry

texts:
I'm trying to write a conditional that adds a class of 'here' to a navigation menu item if segment_1 of the URL matches the URI of the entry I'm specifying. But it isn't outputting anything, so I'd appreciate any help with this, thanks. Here's my code:

{% set about_entry = craft.entries.id(17).first() %}

{{ about_entry.title }}

This conditional works fine if I change '{{ about_entry.uri }}' for a hard-coded 'about', but I want the URI to be dynamic in case it gets changed in the future/


texts:
In the Globals I have a field which is of type table. I was trying to access this table in the javascript in order to get the values of particular rows.

<script>
        var myTable = "{{ craft.globals.getSetByHandle('myGlobal').myTable }}";
</script>

It returns a string "Array". If I put [] around the expression, it will return ["Array"].

Do you know a way to get access to this table?


texts: Are plugins necessary for these 2 things?

texts:
I'm working on migrating an existing project, that is currently made in CodeIgniter and I'm trying to port it to Craft. Everything is great except...

I'm running into two issues:

Have a page counter (view count)

Looking at things, it seems any add/update functionality needs to go via a Plugin. Is that correct? For a simple update:

update  results
set     clicks = clicks + 1
where   id = ".$articleID."

I need to write an entire plugin/module?

I'm using MySQL's NATURAL LANGUAGE SEACH, which just changed the Query a bit,  which is nothing more then:

SELECT             *
FROM            content
HERE            MATCH (title) AGAINST ('super keywords' IN NATURAL LANGUAGE MODE)

I need to also make a Plugin?

I'm a bit in a hurry and don't want to completely dive into plugin development for these quite forward issues.

Can anyone tell me when I'm using pluginfactory.io - to get started - which of these settings I have to switch on? Controllers? Elementtypes? Records? Services? Tasks? Utilities?

I hope I'm wrong and could implement these things more directly...


texts: Path and Entry Template problems when developing locally

texts:
I feel this a simple problem to fix, but I can't find an answer anywhere.

I am developing locally on using MAMP.

Everything on my site is working great until I call up page using a template inside a folder inside the templates directory. At that point the paths are broken to any and all assets (CSS, images, etc.)

For example, if I set the Entry Template for a section in Craft to say news/_entry and then view a news article page... I get an un-styled page.

I am including the CSS like this:

<link rel="stylesheet" href="../public/assets/css/nav.css">

and the images like:

<img src="../public/assets/images/swf_logo.png" alt="" />


texts:
How anyone have any server or database optimization recommendations for running Craft CMS on MediaTemple's GridServer (gs)?

Since it's a shared server, I know there's not as much as you could do with a VPS or dedicated server, but I hope there is something beyond the default settings we can do to keep the site running smoothly.

Thanks in advance!


texts: Multilingual MAMP port number siteUrl issue

texts:
I have my local dev setting up using MAMP on port 8888

  'mydomain.dev:8888' => array(
    // ...
    'environmentVariables' => array(
        'basePath' => '/Users/mypath/SiteCode/mydomain/dev/',
        'baseUrl'  => '//mydomain.dev:8888/',
        'logDumpMethod' => 'print_r'
    ),
    'logDumpMethod' => 'print_r',
    'devMode' => true,
    'useCompressedJs' => true,
    'siteUrl' => array(
        'en' =>  'http://mydomain.dev:8888/en/',
        'ar' =>  'http://mydomain.dev:8888/ar/',
        'zh' =>  'http://mydomain.dev:8888/zh/',
        'fil' => 'http://mydomain.dev:8888/fil/',
        'fr' =>  'http://mydomain.dev:8888/fr/',
        'hi' =>  'http://mydomain.dev:8888/hi/',
        'id' =>  'http://mydomain.dev:8888/id/',
        'ru' =>  'http://mydomain.dev:8888/ru/',
        'es' =>  'http://mydomain.dev:8888/es/',
        'tr' =>  'http://mydomain.dev:8888/tr/',
        'uk' =>  'http://mydomain.dev:8888/uk/',
        'ur' =>  'http://mydomain.dev:8888/ur/'
    ),

),

In the admin general settings I am using {siteUrl} for siteUrl settings. This gets read from the local dev config array as above.

However the admin link on the site in the control panel top left gets the url wrong.
Instead of http://mydomain.dev:8888 it shows
http://mydomain.dev:8888/admin/%7BsiteUrl%7D/

I have other local craft sites setup with port number 8888 O.K. The only difference here is that the siteUrl is specified in a multilingual array.

Is this a bug or am I missing something?


texts: Conditionally Display Content if Section

texts:
How can I conditionally display content if its a specific section?

Currently I'm trying this with no luck:

{% if entry.section == 'lettings' %}{{ entry.rentFrequency.label }}{% endif %}


texts: How to setup assets in multi site where each site should have its own assets?

texts:
I have a setup with multi sites that are separate domains.

site-a.com

site-b.com

I would also like to have assets separate for each site, like so:

site-a.com/images/picture1.jpg

site-b.com/images/picture2.jpg

I tried setting up aliases for each site, but just couldn't get it to work.
Managed to get only one set of aliases to work, in the general.php file, under '*'.
But cannot get aliases to be different for each site, like @web for example.

How would i setup the general.php or volumes.php or env.php to have separate assets for each site?

Additional notes:

I am using the latest version of Craft 3 (Craft CMS 3.0.23.1).

PHP 7.2

The setting "Propagate entries across all enabled sites?" in section is enabled.

The setting "Manage relations on a per-site basis" for asset field is enabled.


texts: Trouble with Custom Command in Custom Plugin. How do I do it?

texts:
I found the documentation here very confusing: https://craftcms.com/docs/3.x/extend/commands.html#module-setup
I've scaffolded a simple test plugin from https://pluginfactory.io/ with "Console Commands" enabled and I've pulled my plugin into composer via 'path'. The plugin shows up fine in the Craft UI, and so I installed it.
However, I can't get the new command to display in the terminal when I do a 'php craft'. Am I supposed to see it?


texts:
I've went through several examples related to my issue, but I quite couldn't find What I'm looking for.

Well, there was one, but with pre-defined array.
What I'm looking for is to only output all my sections, with link and title +  at the matched section's URL, display all entries belonging under relevant section.

I've found here one snippet of code, which logic sounds about right to me, but it's like there's missing something.

{% set sections = [] %}
{% for section in craft.sections.getAllSections() %}
{% if section.type == 'channel' %}
{% set sections = sections|merge([section]) %}
{% endif %}
{% endfor %}

Any help, or direction would be appreciated and I believe, it would help those, Who are like me at the beginning of this journey.

Thank you


texts: Changing asset of entry's assetfield via entries.onBeforeSaveEntry

texts:
I'm trying to add an asset to an entry's assetfield when the entry is saved by using the onBeforeSaveEntry service provided by Craft.

craft()->on('entries.onBeforeSaveEntry', function(Event $event) use ($fileIds)
  {
      $entry = $event->params['entry'];
      if ($entry->section['handle'] == "bildupload" && $event->params["isNewEntry"]){
        $entry->getContent()->useruploads = $fileIds;
      }
  });

Contents of the $fileIds-array are created like so:

$copyrightedImage = craft()->assets->insertFileByLocalPath(
      $tempPath,
      $originalFile,
      $myAssetFolderId,
      AssetConflictResolution::KeepBoth
);

if ($copyrightedImage->isSuccess()){
      $fileIds[] = $copyrightedImage->getDataItem('fileId');
}

This works pretty well for fields such as a formatted text field or the title, but I cant figure out how to change the asset inside an asset field.
The assetfield of the entries in the section bildupload goes by the handle useruploads. How would I go about fetching the assetId, the full Url to the photo or whatever is used here and add the desired photo into the assetfield as an additional used asset?

Thanks for any help or hints.

Edit: I tried following what Brandon described here, but to no avail.
There are no errors thrown, however the assetfield of the entry remains completely empty and does not have any image assigned to it. I'm using closures to use the array $fileIds in the functions shown below.


texts:
So on a cart page, I need to list out the discounts that have been applied to a cart. I need to list them one by one, but only discounts that are applied with a code. I'm having trouble figuring out how to get the discount code, and I need to output the code. Something like this:

Item Total: $200.00
Promotional (25OFF): -$25.00
Promotional (FATHERSDAY): -$10.00
...

I'm looking over the discount info like this:

{% for discount in cart.adjustments %}
    {{ dump(discount) }}
    <br>
{% endfor %}

I don't see an accessible code variable jumping out at me. The only places I can see pulling it is from the optionsJson string, but that is not practical as Twig doesn't have a default JSON filter to decode.

So I can get the discount ID easily enough from that loop; but I'm not sure how to pull a Discount model based on ID. I'm not super versed with Craft and Twig, so I'm hoping there is a simple solution to look up Discounts based on discount ID.

So like this:

{% for discounts in cart.adjustments %}
    {# look up discount based on discount.id #}
        {% if discount.code | length %}
            Promotional ({{ discount.code }}): {# discount amount, probably have to do math here if it is a percentage #}
        {% endif %}
    {% endfor %}
{% endfor %}

I imagine I'm going about this wrong.


texts: How to lock down entries to specific levels of Craft CMS Structure

texts:
I’m trying to figure out a way to setup a simple Craft section: a list of projects, each project consisting of a title and a type; and a series of photos, each photo having a description.

BUT... If I do this as a structure, the client is then able to nest them in a nonsensical hierarchy, like adding projects as children of photos. I know that's going to confuse my client. A way to lock down entries to a specific level would be sufficient, but I'm not finding that...


texts: how to check for the 2nd, 3rd, 4th… image in an asset's field

texts:
I am currently "translating" our current website, which runs on the lastest expressionengine, to craft. we use imagegrids that are arranged by css.

so in an entrie's pulldown field choose between several grids (named q1, q1q2, etc.) and checked via conditionals in the code to know how to style the images and to give them the right "transformations"/sizes:

{# Imagegrid #}

        {images_start}
            {images_start:file}
                {# A (1 landscape) #}
                {if imagearrange == "q1"}
                    {if images_start:count == 1}

                    {/if}
                {# B (2 landscape) #}
                {if:elseif imagearrange == "q1q2"}
                    {if images_start:count == 1}

                    {if:elseif images_start:count == 2}

                    {/if}
                {# C (1 landscape / 1 portrait) #}
                    {if:elseif imagearrange == "q1h2"}
                        {if images_start:count == 1}

                        {if:elseif images_start:count == 2}

                        {/if}
                {# C1 (1 portrait / 1 landscape) #}
                    {if:elseif imagearrange == "h1q2"}
                        {if images_start:count == 1}

                        {if:elseif images_start:count == 2}

                        {/if}
                {# D (3 portraite) #}

now I want to bring this functionality to craft – and I already checked out how to check for the fields values e.g. {if:elseif imagearrange == "h1q2"}.

but: I can't figure out how to check for the 1st, the 2nd, the 3rd image in an asset field, like {if images_start:count == 1} in ee.

since craft seems in many ways more efficent than ee maybe this would be solved completely different and I am absolutely open to learn new ways of doing this.

thank you very much!


texts: Is there a prescribed way to to represent complex field types as strings?

texts:
I've found the need lately for a way to represent complex fieldtypes like Matrix, Entries, etc as strings. e.g. in the following plugins:

https://github.com/boboldehampsink/auditlog
https://github.com/boboldehampsink/export

Currently, it seems like you have to more or less account for every fieldtype and do some special processing.

I'm wondering if there is a method that every fieldtype can use (__toString or other) to do this kind of thing in a unified manner.

I was looking at how Craft does the Matrix "preview" for collapsed rows, but I think that's just all JS.


texts:
I am trying to update the value of an Entries field on an EntryModel, however I am having a lot of trouble getting it to update correctly.

I've tried allocating both an entire EntryModel and its id but neither seems to set the value, e.g.

$comment = new EntryModel();
$comment->sectionId = $commentSectionId;

$comment->setContent(array(
    'createdBy' => $user // or
    'createdBy' => $user->id
));

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

Where $user is a valid EntryModel.

The comment saves fine, the createdBy field just has no value. I guess I am using the wrong data from $user but I have having a very hard time finding any thorough documentation around setting different kinds of EntryModel data.

This is the entire bit of code I have, if it helps:

class Bugr_CommentService extends BaseApplicationComponent
{

    public function post(EntryModel $user, EntryModel $ticket, $body)
    {
        $comment = new EntryModel();
        $comment->sectionId = craft()->sections->getSectionByHandle('comments')->id;

        $comment->setContent(array(
            'createdBy' => $user,
            'ticket' => $ticket,
            'body' => $body
        ));

        return craft()->entries->saveEntry($comment);
    }

}


texts: How do I write a conditional for whether a section contains entries?

texts:
I've got a blog section on a page but want to hide it if there are no blogs.

{% set blog = craft.entries.section('blog').limit(5) %}
{% if blog !='' %}
  <div class="something">
    {% for entry in blog %}
      ...
    {% endfor %}
  </div>
{% endif %}


texts: Trying to replace an asset via replaceFile action in entry form

texts:
UPDATE: We've resolved this one. Here is the working code:

<form method="post" enctype="multipart/form-data" action="" accept-charset="UTF-8">
  <input type="hidden" name="entryId" value="{{ entry.id }}">
  <input type="hidden" name="action" value="entries/saveEntry">
  <input type="hidden" name="sectionId" value="2">
  <input type="hidden" name="enabled" value="1">

  <input type="file"
         name="replaceFile-{{ asset.id }}”
         class="replace-file"
         data-id="{{ asset.id }}" />

...and...

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(".replace-file").change(function() {
  var url = '/actions/assets/replaceFile',
      fileId = $(this).attr("data-id"),
      file = $("[name=replaceFile-"+fileId+"]")[0].files[0],
      formdata = new FormData();

  formdata.append("replaceFile", file);
  formdata.append("fileId", fileId);

  $("#output").html("Uploading...");

  $.ajax({
    url: url,
    type: 'POST',
    data:  formdata,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data) {
      $("#output").html("Supposedly worked...");
    }
  });
});
</script>


texts:
I am migrating a static HTML site to Craft, and trying to apply image transforms to specific images without running them through a Craft field.

In other words, I have the image path hardcoded in the template, and would like to apply an existing transform to it.

I have tried to set my image path as a Twig variable and then call getUrl('medium') on that - but i get the error because I am passing a String value.

I also tried to store the image path in an array variable, but it's not working either.

Is there anyway to achieve this and pass a static path to getUrl()?


texts: How to get a field value from next/prev asset

texts:
asset.getNext().fieldName does not work but might help explain what I was aiming for.

To be more specific, for where there are multiple images in an entry, I want to assign a class to each depending on its next image’s field value. Also, the field I’m trying to get a value from is a radio field.


texts:
I've got a site with several locales and want to reuse a set of categories across locales but want to target a locale specific template from within each.

Is it possible to set a locale-specific path within the category group settings, eg

{{ craft.locale }}/_video

Cheers,

Cole


texts:
I keep getting a server error when attempting to save data to a table field. This is the code I am using test data insertion. (251 is a valid enteryId)

    $entry = craft()->entries->getEntryById(251, $localeId = null);
    $arr = array('col1' => 'some sku', 'col2' => 'This is a big fat description', 'col3' => 495.00, 'col4' => 0);
    $arr = json_encode($arr);
    $entry->getContent()->gistDistribution = $arr;
    $success = craft()->entries->saveEntry($entry);

This is my error:

Internal Server Error
Illegal string offset 'sku'

Note: sku is a column name in my table field.


texts: How can I check a user has completed a field in their profile after log in?

texts: I'm sure I've seen this documented somewhere but can't for the life of me find it. After login I need to check the user's profile for an empty field (e.g. phone number) and redirect them to a reminder to complete that field if empty. I guess this can be done via an intermediary page but I'm sure I saw a better solution somewhere. Any help?


texts: Is it possible to manage language translations without directly accessing the PHP translations file?

texts:
It is beautifully described in the docs how to translate static text using translation files.

As the client has no access to that file and managing a php array is not what I want them to do, I am looking for a way to make edits to the translation file feasible directly in the Control Panel.

This would allow me to set things up in the template and then hand off the actual translation work to someone else.

Yes, you probably have to write a plugin for that. But can you edit the files from a plugin? Is there any API or service available that might help?


texts: Craft CMS Shows 404 Error on Admin Pages

texts:
I'm trying to take a live / currently well functioning production site and create a local version. I downloaded all the files and the database and the site itself now works on my local device but whenever I try to access any of the admin pages to edit the site, I get a 404 page from Craft.

I replaced my entire craft/app folder to help ensure no corrupt file issues and that didn't fix the problem. I also completely deleted the contents of my craft/storage/runtime folder to account for the potential download of temp files that could be confusing the local site and that didn't fix it either.

The local site is running in dev mode and there is no error that shows on any of the admin pages, just a 404.

Any idea what's going on here and possible fixes?

Thanks!


texts:
My site is built on a single structure section called "pages". It includes 4 entryTypes.

One of the entryTypes is called "contact" and includes a MatrixBlock that displays fine on the contact page.

I'd like to make use of those entries (from the Matrix Block) in the site's footer (on all pages). Here is where I started:

{% for block in entry.MatrixFieldHandle.type('MatrixBlockHandle') %}
{{ block.title }} etc...
{% endfor %}

This only works on the contact page itself. How can I display a Matrix Field elsewhere than on its own page?


texts:
I've got an events listings which works pretty well and there is a:

Custom Date field, eventEnd (just date)
Custom Start Time, eventStart (just time)
Custom End Time, eventEnd (just time)

I can list these entries so we list by date then time by using:

{% for entry in craft.entries.section('events').order('eventDate', 'eventStart').find() %}

but eventStart is ignored altogether, even when I would use:

{% for entry in craft.entries.section('events').order('eventStart').find() %}

I would expect:

Event 1: 14:00
Event 2: 15:00
Event 3: 16:00

but instead get something more random based I think on post date.

Suggestions welcome thank you!

UPDATE:

my biggest issue is actually being able to list by eventStart at all. Just using {{ eventStart }} reveals the current date. But if I try to boil down to just the hour, it's not a recognised way of ordering (even though it's just a set of numbers?)

So, I'm not sure where to head with this. I'm sure that if my start time was bundled in with the main date, all would be fine, but it makes the system a bit less obvious and flexible.

Here's what I've tried:

{% set completeeventlist = craft.entries.section('events') %}
{% for x in craft.entries(completeeventlist).order('eventDate') %}

    {% set es = x.eventStart|date('H') %}
        {% for entry in craft.entries(x).order(es) %}

{{ entry.id }}{{ es }}

    {% endfor %}

{% endfor %}


texts: TWIG dataUrl function for resized images

texts:
Craft provides the very nice TWIG function dataUrl(pathToImg) to inline images in e-mails.
E.g.

will base64 encode the image into the src. This also works if you pass in an instance of an asset:
{% set myAsset = craft.assets.id(123).one() %}

My question: Does anyone know how to resize the image first, if you pass in an asset?
This does not work:


texts:
I have a matrix block attached to my user, the block handler is children and has one field dob date filed something like this:

fields[children][420][fields][childrenDateOfBirth][date]

The problem is that I would like to update the date right before the user is saved. So I have an envent listener in my plugin

craft()->on('users.onBeforeSaveUser', function(Event $event) {

    $matrixData = array();
    $matrix     = $event->params['user']->getContent()->children;

      foreach ($matrix as $block){

        $blockData = array(
                            'type' => $block->getType()->handle,
                            'enabled' => $block->enabled
                           );

         $blockData['fields'] = array(
                           'childrenDateOfBirth' => array('date'=>'2000-10-10')
                        );

          $matrixData[$block->id] = $blockData;

  }

 $event->params['user']->getContent()->children = $matrixData;

}
  ...............

And I get this error : Fatal error</b>:  Call to a member function getType() on array Is there a way to do this?


texts: Force Field Limitation in Drafts - Front End Form

texts:
I'm not sure if this is a two part question yet. I need to enforce field limitations (specifically, character limits for plain text fields) when working with drafts. In the CP, I discovered that drafts ignore all limitations related to character length and only throw errors when attempting to publish the draft.

I'm assuming that enforcing the draft field limitations in the CP will also apply to front end entries that are saved as drafts as well. If not, this is what I'm doing:

I have a front end form for user created entries. Everything has been working correctly with the exception of field limitations (users submit draft revisions until published by an admin).

Any idea how to force field limitations for a draft?


texts: Route that should be matching numbers not matching a zero?

texts:
I have the following in my routes.php file:

return array(
    'articles/(?P<sectionId>\d+)/(?P<offset>\d+)' => 'articles/index'
);

And while localhost/articles/4/1, for example, routes properly to the template, localhost/articles/4/0 does not and I instead get a 404.

Is there an issue with zeros being picked up as valid URI segments?


texts:
I have a multisite and it seems that the lineitems are always saved in the default site's language. When I loop over order.lineitems the item.description isn't translated.
When I look at the order in the CP, I can also see that the title of the variants (description) is in the default site's language.
Is this normal and if so, how can I change this?


texts: Craft 3: Get Data from a custom Table via createCommand()

texts:
In Craft 2 you could creat a query with:

craft()->db->createCommand()->select() .... etc.

But in Craft 3 there is no select() Method in Craft::$app->db->createCommand().

Am I overlooking something?


texts: Barba.js (with gsap) 'leave' and 'enter' hooks not working in Craft 3 - same code works in WordPress

texts:
The below code (Barba/gsap) works as expected in WordPress, but in Craft 3 only the 'once' (i.e. not the 'leave' and 'enter') hooks fire.
There are no errors or anything unusual in the Barba debug console output.
I'm using Laravel Valet, browserSync (gulp) for both WordPress and Craft local environments.
I follow the DOM structure outlined in the Barba.js docs here: https://barba.js.org/docs/getstarted/markup/
Any ideas on why Barba may not play nicely with Craft (as opposed to WordPress) and/or my local dev setup, or any known workarounds etc., would be much appreciated.
import barba from '@barba/core';
import gsap from 'gsap';

const animationEnter = (container) => {
  return gsap.from(container, { autoAlpha: 0, duration: 2, clearProps: 'all', ease: 'none' });
}

const animationLeave = (container) => {
  return gsap.to(container, { autoAlpha: 0, duration: 2, clearProps: 'all', ease: 'none' });
}

barba.init({
  debug: true,
  transitions: [
    {
      once({next}) {
        animationEnter(next.container);
      },
      leave: ({current}) => animationLeave(current.container),
      enter({next}) {
        animationEnter(next.container);
      }
    }
  ]
})


texts:
Is there a way to add tel: links in the Redactor WYSIWYG?
I tried Link > Insert link to enter tel:+43123456789 as URL,
but all I got was <a>+43123456789</a>. The href is missing.


texts:
I moved my website from my local dev environment to my production server, but my admin assets are not resolving. I tried everything but didn't work. In fact it's probably a problem on the server side, but I cant do anything about it.

Now, is there a way to hardcode those assets in the admin pages ?
Thanks for your help !


texts: What are the advantages/disadvantages of the various cloud storage solutions for assets?

texts:
When setting up a new assets source, Craft allows you to natively connect to one of these cloud storage solutions (assuming you're using the Craft Pro edition):

Amazon S3
Google Cloud Storage
Rackspace Cloud Files

I know that the answer may be subjective, but want to hear pros & cons from people who have tried any of these. I'm working on a project which will require one of these solutions, and I greatly value the opinions of this community.


texts: Is there a way to allow users to control alignment of images in the Redactor plugin using Craft 3

texts:
I'm looking to let editors determine the alignment of images in a Redactor field.

I wasn't sure if it worked out of the box with Craft 3 (I'm using 3.0.9).

I did find this plugin: https://github.com/picdorsey/craft-redactorimageposition but it looks like it is Craft 2 and I don't see any forks that are updated for Craft 3.

Any suggestions on how to let users in the Control Panel control alignment of images in a WYSIWYG field would be very helpful. (This link suggests using a Matrix field, but I'm not sure how that would give the user control: Using the Redactor rich text field, how can I dynamically wrap my images with a fancyBox link (with attributes as parameters)? )


texts: Adding dynamic second email address to Contact Form plugin

texts:
According to the Contact Form plugin docs, I can do:

<input type="hidden" name="toEmail" value="{{ 'name@domain.com, name2@domain2.com' | hash }}">

That seems to work fine, but one of those email addresses I want to add dynamically. I've tried the following, but none seem to work, generally sending to just the second email address:

{# adding first email as var #}
{% set firstEmail = 'name@domain.com' %}
<input type="hidden" name="toEmail" value="{{ firstEmail ~ ', name2@domain2.com' | hash }}">%}

{# adding first email as var and avoiding | hash #}
{% set firstEmail = 'name@domain.com' %}
<input type="hidden" name="toEmail" value="{{ firstEmail ~ ', name2@domain2.com' }}">%}

{% set firstEmail = 'name@domain.com' %}
{% set emails = firstEmail ~ ', name2@domain2.com' %}
<input type="hidden" name="toEmail" value="{{ emails | hash }}">
{# RESULT: <input type="hidden" name="toEmail" value="505103f2971d445c709c131b8eee0a59e3ff668bname@domain.com, name2@domain2.com">#}

{# adding first email as var with extra quotes #}
{% set firstEmail = 'name@domain.com' %}
{% set emails = "'" ~ firstEmail ~ ", name2@domain2.com'" %}
<input type="hidden" name="toEmail" value="{{ emails | hash }}">
{# RESULT: <input type="hidden" name="toEmail" value="e3a44b3632212521351d8d44af34742a63f6516e'name@domain.com, name2@domain2.com'"> #}

Any ideas?


texts:
We have a website that has around 80k users per month and we're updating around 1k entries per night due to stock updates. The site's been live for almost 2 years and the CMS has become really slow and almost unworkable. The front-end seems pretty good due to cache but slow without it.
After doing some digging, I noticed the table 'elements_sites' in phpMyAdmin has 1.45m rows. with all but 9k of these showing a NULL slug and uri. It seems like its got loads of 'junk' in there but I don't fully understand it. The 'elements' table has 486k rows, 'content' has 466k rows.
Here's what I'm trying to figure out so any pointers would be great.

Should 'elements_sites' be around the same number of rows as 'elements'?
Is it possible to somehow check what's still relative and in use and clear out the rest?

We've updated all plugins and Craft CMS to the very latest versions. We've had the Wishlist plugin installed from day 1 and when we experienced a slow CMS, we uninstalled then reinstalled and it worked much faster again (it creates a row/list for every user). Tried doing this recently but no joy. My hunch is that it has left loads of rows in there since updating over the years.
If anyone has any ideas, that would be awesome! (hope all this makes sense ;) )


texts: Does Craft have a bookmarklet to quickly post/save content from the web?

texts: Does Craft have a bookmarklet that allows you to quickly post images, text, videos or any other content from web pages to Craft entry types/fields?


texts:
I am an in-house graphic designer with virtually no experience with building websites.
My company has a website built with Craft for which we have an admin to change some content like images and tables.
Some pages are not customizable at all. It seems they might have been constructed only with CSS and HTML. I don't know.
Now, we need to change these pages and build new ones using the same structure.
The agency that built the website seems to be ghosting on us so we have to find a solution to make the changes ourselves.

How do I access the code with my admin?
Is is possible that the guy who built the site restricted our access to the code?


texts: How can I ensure certain items always display at the end of a list?

texts:
I have a website where I want to show Power Coat (-PC) options at the end of a list. The data goes into Craft in an unpredictable order, from a third-party service, so I am responsible for organizing it in the front-end.
Is there a way I can split out or force the -PC items to always appear at the end of the list, in my template?


texts:
What is the correct Validation Pattern format to add to a Formerly email field in the Craft admin control panel if I want to stop any submissions from email addresses with a .ru TLD?

I've tried:

!(\.ru)
/^((?!\.ru).)*$/s

But they do nothing.


texts: Returning entries based on Relationships across different category groups using 'and'

texts:
I'm trying to figure out how to set up my relatedTo paramaters to do a category search. Normally it's not a problem but in this case I need something more complex than normal.

I have multiple category groups. Within each group I need to use an "or" condition. So entries are returned if they match any categories in that group.

But across the different groups I need to apply an "and" condition.

i.e. Group 1 is "colours", Group 2 is "size"

So if someone selects:
Group 1: black, blue
Group 2: small

I want to return any entries that are (black OR blue) AND (small)

Setting the 'or' condition within a group is no problem but I'm stumped on how I can merge the different sets of parameters together to get the desired results.

This is a truncated version of what I have so far, just showing 2 of my groups.

{# clear everything #}
{% set colourQuery = '' %}
{% set sizeQuery = '' %}

{# get all the search query parameters #}
{% set colour = craft.request.getParam('colour') %}
{% set size = craft.request.getParam('size') %}

{% set colourQuery = colour | join(',') %}
{% set sizeQuery = size | join(',') %}

{# colour #}
{% set colourParams = ['or'] %}
{% set cats = craft.categories.group('colour').slug( colourQuery | split(',') ).find() %}
{% for cat in cats %}
    {% set colourParams = colourParams | merge([{ targetElement: cat }]) %}
{% endfor %}

{# size #}
{% set sizeParams = ['or'] %}
{% set cats = craft.categories.group('size').slug( sizeQuery | split(',') ).find() %}
{% for cat in cats %}
    {% set sizeParams = sizeParams | merge([{ targetElement: cat }]) %}
{% endfor %}

Then I build the criteria... I'm sure this is where I'm going wrong

{# build criteria #}
{% set relatedParams = [] %}

{% set relatedParams = relatedParams | merge(colourParams) %}
{% set relatedParams = relatedParams | merge(sizeParams) %}

I've also tried

{# build criteria #}
{% set relatedParams = [
        ['and', colourParams],
        ['and', sizeParams],
    ]
%}

I'm using relatedParams like so:

{% set products = craft.commerce.products('products').relatedTo(relatedParams).order(sortString).limit(numPerPage) %}

So, my question is how should I join those different paramater arrays in order to get what I need?


texts: Searching on whole title returns no results

texts:
When a client site is searched by the whole title, the search results return zero.
If I search by a few words in the entry title then the entry is returned in the search results.
If i search with the whole title in quotes, I get the entry in the search results.
I am expecting the entry to be returned when searching on whole title.
So is this a bug to file or mismatched expectation?
Search query :
results?q=Help+for+seafarers+when+they+need+it+most


texts:
I have the following text search input field:

<form action="{{ url('search') }}">
    <input type="search" name="q" placeholder="Search">
</form>

I would like to search each keyword in the user's query with the OR logic as per Craft docs.

  salty OR dog  containing either “salty” or “dog” (or both).

How can I separate the user's text search for "salty dog" so that the search query returns results for "salty" or "dog" instead of only for results containing "salty dog"?

Below is how I currently have the search set up in the template:

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search('*' ~ query ~ '*').order('score') %}
{% paginate craft.entries.search('*' ~ query ~ '*').limit(10).order('score') as pageInfo, pageEntries %}

I have fuzzy search enabled via config:

'defaultSearchTermOptions' => array(
   'subLeft' => true,
   'subRight' => true,
),


texts: How to show nothing when you leave an input field empty in the entries instead of showing an error?

texts:
I made a content page (Channel) where the client can add a bunch of content. There will be multiple pages (1 page for every case) with the same layout. Sometimes they don't want to fill in every input field or asset. When they leave a field blank, I get an error.

Is it possible to just not show the parts they didn't fill in?
For example: When I put the website in 'production' they show the broken IMG instead of nothing.


texts: Missing Matrix row types on output after upgrade to Craft 3 (subsetting and cloning ElementQueries)

texts:
Update: Now I know the cause of my problem, I have appended to the original question title to try and help other people stumbling across the same issue.

I have a pending support ticket open with P&T on this, but just wondering if anyone else has had a similar experience and might be able to point me in the right direction.

I have a development site running happily on Craft 2.6.3013. As a first foray into Craft 3 I thought I would upgrade it to Craft 3 in a dedicated folder and DB of my local setup.

All seemed to go fine. I worked through and eliminated deprecation errors in my 2 well developed templates.

But one of the templates utilises a Matrix field with 2 block types -- subsection and item -- and only subsection rows are publishing.

The 20 rows originally in the field (in its singles entry) are all there in the back end, and their respective types show up as they should there: 5 for subsection and 15 for item.

But a simplified front end loop of:

    {% for row in entry.timeline.all() %}

{{ row.type }}

    {% endfor %}

…only produces the following outcome:

subsection

subsection

subsection

subsection

subsection


texts: How do I actually add a Digital Product to an order?

texts:
I'm trying to use the fresh new Digital Products plugin in my website.

I managed to create some products and assigned licenses, I see some  licenses when I log in as an end user - but the last link is missing.

What is the process of getting a specific product object in my "digital product detail page", adding it into the order along with other products, paying and getting the license auto generated?


texts: Copy of subsite is still serving index.php in the links?

texts: I have 2 subsites on the same apache server both pointing to the same craft database.  The original subsite has the normal links, but, the subsite copy has index.php in all of the links.  Can someone point me in the right direction to remove the index.php references? NOTE: .htaccess is correct and the same on both sites.


texts:
The slider requires an unique ID per slide, wrapped in
 tags, so I am trying this:

    {% for testimonials in craft.entries.section('testimonials').limit(3) %}

            {{ testimonials.body_testimonial }}

            {{ testimonials.title }}

    {% endfor %}

This results in the first slide entry with both Title & Body, but the second and third slides only parse the Title not the Body.

Could someone verify the craft code is correct? The entries are made in a Channel section with a handle; testimonials.


texts:
Just downloaded FeedMe, and it seems like a great solution to what I want to do, but I can't get it to succesfully run a json import on a feed generated by instagram. When I hit 'Save and Continue', I get a PHP warning:

file_get_contents(): php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known

It's on this line:

 public function getRawData($url)
     {
     if (file_get_contents(__FILE__) && ini_get('allow_url_fopen')) {
         $content = file_get_contents($url);
     } else if (function_exists('curl_version')) {
         $curl = curl_init();
         curl_setopt($curl, CURLOPT_URL, $url);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         $content = curl_exec($curl);
         curl_close($curl);
     }

     return ($content) ? $content : false;
 }

It's worth noting, I have no idea what to set the Primary Element as. Didn't see any documentation for JSON on the readme


texts: Craft Commerce: fixed product variants/multiplier

texts:
We have a client that is selling products with fixed rate variants. In other words so that the base cost is the only price defined whilst others are based on a globally defined multiplier, eg. 1.5x or 3x the base/defined price.

Is there a way (either baked in or via plugin) to have extra variants created or available based on a pre-defined criteria/multiplier? If necessary happy for this to be just in the add to cart/checkout process rather than explicitly defined in the product details/record.

Looking through docs only way could see something like this being possible would be via a plugin automatically adding/updating variants on a product creation/save eg the EVENT_BEFORE_SAVE_ELEMENT event.


texts: Locale case sensititvity on AWS instance

texts:
I have a multilingual Craft CMS site working perfectly on my local instance, OS X 10.10.5 running Apache 2.4.16, and so I moved the site to AWS, Amazon Linux 4.1.13-18.26.amzn1.x86_64 also running Apache 2.4.16, however, all of my locales are now case sensitive!

On my local I have
http://<site>/en_us/page
on AWS this gives me an error, The requested URL /en_us/page was not found on this server., a hard 404. [i.e. not the templated 404 page I have configured in craft for missing content]

However, when I use http://<site>/en_US/page, i.e. using the ISO standard capitalisation for the country code, I get all of the content perfectly fine. All of my links, and configuration, is of course based upon the lowercase way that Craft normally uses locales, and so the links are all broken on AWS.

I have also noticed that the CP URL is using a querystring on AWS instead of rewriting; i.e. /en_US/index.php?p=admin/settings/locales instead of en_us/admin/settings/locales [which may be a related issue]

As the rewriting for the CMS works, /en_US/page actually gets the right template and content, I am puzzled as to what I may have missed in configuring my AWS instance.

Has anyone seen anything like this, or have some pointers?


texts: Dropdown template URI breaks on language switch

texts:
I have the following code in my header of a multilingual site. It produces the correct urls in english.

{% for entry in menuentries %}

    {% if entry.entryLink.first|length %}
        {% set navlink = entry.entryLink.first().uri %}
    {% elseif entry.customMenuUrl|length %}
        {% set navlink = entry.customMenuUrl %}
    {% endif %}

    {% if entry.level == 1 and entry.children|length %}

            {{ entry.title }}

                {% for child in entry.getDescendants() %}

                        {{ child.title }}

                {% endfor %}

    {% elseif entry.level == 1 and not entry.hasDescendants() %}

            {{ entry.title }}

    {% endif %}

However when I switch languages eg. to french the child.entryLink.first().uri returns null. Even if I just change the en to fr I get the same result. Bit confused.


texts: How to conditionally hide particular plugin settings?

texts:
This answer has given me most of what I need, but I'd like to hide certain settings based on the status of other settings. CP seems to have nice functionality built in for conditionally hiding/showing parameters. For example, when changing a field from Rich Text to Plain Text, several options disappear.

In this case, only if the preceding checkbox is checked do I want it to give an input field for the category field handle.

Here is my /craft/plugins/calendar37/templates/_settings.html file:

{% import "_includes/forms" as forms %}

{{ forms.checkBox({
        label: "Event Hyperlinking"|t,
        id: 'eventClickDestination',
        name: 'eventClickDestination',
        instructions: "If checked, clicking on an event goes to Category page. Otherwise, unchecked it will go an Entry page"|t,
        value: settings.eventClickDestination,
        errors: settings.getErrors('eventClickDestination')
    })
}}

{{ forms.textField({
        label: "Category Field's Handle"|t,
        id: 'categoryFieldHandle',
        name: 'categoryFieldHandle',
        instructions: ""|t,
        value: settings.categoryFieldHandle,
        errors: settings.getErrors('categoryFieldHandle')
    })
}}

Note, I'd like to work out similar functionality with a 3-part radio button, but haven't figured out how to do radio buttons yet.

Thank you!