texts: Day and month names ignore certain formats in date filter and revert to number

texts:
When I try to output the day name (l or D) or month name (F or M) i get a number instead of the day/month-name.

{{ entry.end|date("j. F Y") }}

turns into:

1. 9 2015

when output.

Expected output would be 1. oktober 2015 (site language is Norwegian (nb)) or even 1. October 2015 (if internationalization did not work).


texts: How to get asset URL from field in template

texts:
I'm new to Craft and having a very hard time calling the URL from a field I created called imagePrimary

I've read this extensively but still no luck. https://craftcms.com/docs/assets-fields

{% include 'header.html' %}

{% block content %}

{% for entry in craft.entries.section('projects').limit(500).find() %}

{{ entry.studio }}{{ entry.title }}

{% endfor %}

{% endblock %}

{% include 'footer.html' %}


texts: Unexpected output from Twig set variable

texts:
My entry has a custom field to set a social image for Facebook.

In the entry template, I'm defining the output like so:

{% set social_image = "" %}
  {% for image in entry.metaImage %}
    {% set social_image = image.getUrl() %}
  {% endfor %}

Then in the layout I have this

<meta property="og:image" content="{% if social_image is defined %}{{ social_image }}{% endif %}" />

and this works great. However, when that field hasn't been, I want to fallback to a custom field that will always have an image set.

I tried to change the layout to {% if social_image is not null %}{{ social_image }}{% else %}{{ social_image_fallback }}{% endif %} setting social_image_fallback within the entry template of course, but that outputs a null value.

I originally had {% if social_image is defined %} but of course if defined would always evaluate to true.

I'm missing something simple here right?


texts: Commerce - Ajax returning obj.success even when failed

texts:
I've got a basic jQuery script that I use to update the cart, either through the actions /actions/commerce/cart/updateCart (if product isn't in cart yet) or /actions/commerce/cart/updateLineItem (if product is already in cart.

It's been working fine, however I'm noticing the ajax return object is returning with property .success as true even if the product that was added was out of stock. This leaves the user thinking the product was added, rather than being able to say it wasn't and was out of stock.

For example (not the direct code, might have some errors, but the gist of what I am doing is:)

HTML

<form method="POST" id="addToCartForm">
{{ getCsrfInput() }}
<input type="hidden" name="action" value="commerce/cart/updateCart">
<input type="hidden" name="redirect" value="/cart">
<input type="hidden" name="purchasableId" value="{{ product.id }}">
<input type="hidden" name="qty" value="1">
</form>

jQuery .. on submit form

$form = ("#addToCartForm");

var form_data = $form.serializeArray()

form_data.push({
    name: window.csrfTokenName,
    value: window.csrfTokenValue
})

$.post('/actions/commerce/cart/updateCart', form_data, function(response) {

    if(response.success) {
    console.log("success");
    }

    else if(response.error) {
    console.log(response.error);
    }

    else {
    console.log("neither a success nor an error returned.. ¯\_(ツ)_/¯");
    }

});

The problem is that if the product has no stock left, response still returns with success. Right now, I figured the best thing I can do is look inside response.cart.lineItems and see if the new purchasableId exists in there. If not, than I can assume it wasn't added and will just have to use that as an indicator that stock was empty - although that'd be an assumption not always true.

Is this a bug or would there be a reason/mistake that could cause commerce to return .success as true even when the product being added is out of stock?


texts: Are there any plugins or best practices for giving authors in Craft the ability to create footnotes within a Rich Text Field? Is anyone doing anything like this?


texts: Can the Freeform Plugin be used with headless mode in Craft?

texts: Anyone know if the Freeform plugin is compatible with Craft's headless state. Or if there are any other form plugins that are?


texts: What's the recommended permissions configuration for AWS S3 media storage?

texts:
I'm hosting assets for Craft 2.9.3 site on AWS S3.
I'm trying to figure out how to give the site (and its users) access to the files without making them broadly publicly available.
I found a suggestion for the right User/Group permissions here. Those are:
{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "s3:ListAllMyBuckets"
        ],
        "Resource": "*"
    },
    {
        "Effect": "Allow",
        "Action": [
            "s3:GetBucketLocation",
            "s3:ListBucket",
            "s3:PutObject",
            "s3:GetObject",
            "s3:DeleteObject",
            "s3:GetObjectAcl",
            "s3:PutObjectAcl"
        ],
        "Resource": [
            "arn:aws:s3:::bucketname/*"
        ]
    },
    {
        "Effect": "Allow",
        "Action": [
            "s3:GetBucketLocation",
            "s3:ListBucket"
        ],
        "Resource": [
            "arn:aws:s3:::bucketname"
        ]
    }
]
}

I attached this policy to an IAM Group, in which the IAM User is a member. I am using that IAM User's credentials on Craft 2 for access to the files.
However, I get a 'Access denied" error. The only way I've found to get rid of that error is to grant full public access to the bucket. It doesn't seem right to me that the files are publicly accessible. On the site itself only logged in users have access to many of the assets in the S3 bucket.
Have I missed a step somewhere in this configuration?
UPDATE 20201020
I tried a User policy generated by the tool Billythekid provided in the comments. The policy it created was:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListAllMyBuckets",
      "Resource": "arn:aws:s3:::*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListBucket",
        "s3:ListBucketMultipartUploads",
        "s3:GetBucketLocation"
      ],
      "Resource": "arn:aws:s3:::MY-BUCKET"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:AbortMultipartUpload",
        "s3:DeleteObject",
        "s3:GetObjectAcl",
        "s3:GetObject",
        "s3:PutObjectAcl",
        "s3:PutObject"
      ],
      "Resource": "arn:aws:s3:::MY-BUCKET/*"
    }
  ]
}

After applying this policy to the User, I still get AccessDenied error from AWS when trying to access the file from the site. Yet when I run the appropriate tests in the IAM Policy Simulator, everything is accessible as expected.
The only way I've found around this is to set a policy on the bucket which grants public access (e.g., a policy that has "Principle": "*" field/value in it, along with the necessary actions, etc.
As a workaround, I've set a aws:Referrer condition, so that only the site in question can reference the files.
So I am back to my original question ... How does one set up AWS S3 for Craft without granting public access to the bucket? For example, I don't have this issue when I give Wordpress storage plug-ins AWS S3 storage access (i.e., public access is blocked, and Wordpress doesn't get an access denied error from AWS.


texts:
I'm not sure if I've been using asset volumes correctly.

For each folder inside my /uploads directory, I've been creating a new volume. So they're all relative to /uploads

I have volumes for things like blog, general, locations, brochures, etc.

so folder structure is like:

 - Uploads
    - general
    - blog
        - subfolder
    - locations
    - brochures

Should I just have a single Volume called "uploads" and then create the subfolders within the craft dashboard via Assets?

Is there a downside in creating a volume per folder?


texts: Is it possible to use something like dropzone.js for file uploads with sprout forms?

texts:
I'm trying to come up with a nice UI experience for people to upload a CV and covering letter and I'm considering using something like http://www.dropzonejs.com/

I'm not sure how this would work with sprout forms because you have to put a action in the form to make it work (from what I can tell anyways)

Is there a solution for this or is there an alternative approach you know that would work?


texts: How to update from a very old version of Craft?

texts:
I'm trying to update an old site that is still running on Craft 2.2 (from September 2014), but unfortunately the update process to the current version (2.6) breaks.

Does anyone have any experience of upgrading a Craft site from several versions back? I'm thinking my best bet might be to try doing it in a series of steps by downloading intermediate versions from here. I'm wondering though if there are particular version numbers that are good milestones for updating (or best avoided)? (I half remember a version that had to be manually installed a while back) Or alternatively, whether there's a better approach I haven't thought of?

Update: the problematic step seems to be upgrading to 2.5. I've managed to run updates up to the last build of 2.4 but the jump from 2.4 to 2.5 always seems to fail. The error message is just "There was a problem updating your database", so it's hard to know what exactly is going wrong.


texts: Download images uploaded in backend with Sprout Form Plugin

texts:
I'm using sprouts form for craft and I built a form with a file upload field. It works fine but the problem is that in the backend form entries, I can only see the uploaded image as a thumbnail (img attached).

Is there anyway to download the image from the backend? or at list get the link to open it with the browser in full size?


texts: Why is Craft returning a 504 during a system update?

texts:
There have been a few updates to the system and some of the plugins I am using. I have installed everything locally and a plugin needed to run new migrations as a result of the update.

Everything works great locally, I went to /admin to "Finish up" the updates.

Now I have moved the files out to my staging server. I always manually update (even though Craft will do this for me). Once all of the files have deployed, I once again visit /admin to run the migrations.

However, the database is quite large (> 100MB) and I am getting a 504 Gateway timeout error.

What can I do to fix this?


texts:
I'm still new to CraftCMS and still learning about site structure. The site that I am asking about below is not (yet?) in CraftCMS:
Our site is composed of many subsites which have different users contributing to them. Would it be possible within CraftCMS to restrict a user's login to only viewing the content that they can edit (ie- within their 'subsite' area)? I say viewing (not editing) since we have a LOT of content and I'd like to keep the content accessibility separate for different users to prevent confusion.


texts: How do I send PayPal the Craft Commerce Order Number?

texts: The client is using PayPal Express for the payment gateway. When orders are placed, Paypal shows the ID for the order, not the Order Number. Is there somewhere I can change that?


texts: Corruption of Link to an Entry links within Rich Text field

texts:
On a local government website running Craft CMS a lot of in-body links are effected with the Link to an Entry function within the Redactor editor. I have encouraged the content editors to use this instead a directly coded URL on the basis that if the linked-to entry changes location the link will still work. So far so good until sometime in the last week around 140 of these internal links corrupted.

So what used to be

Please see Schedule of fees and charges

became

Please see Schedule of fees and charges

and of course no longer work.

Understandably there is a lot of upset, both around the fact that access to important documents is no longer available, and that fact that someone has to find and repair 140 links, and then check that they were repaired correctly.

Can anyone offer any suggestion as to how this may have happened? All I can offer is that a Pending Task held up the task list for a while (I don't know how long). The task hadn't failed but after seeing no action on it for a day or so, I deleted it and this caused a backlog of tasks to run. While I don't know if there was any connection, but the timing of the start of the problem does match the running of the tasks.

The links have also been changed in all the entry revisions. At first this made me suspicious that they were never right, but as we run a link checker looking for broken links around once a month, or whenever a bigger set of edits have been made, I can confirm that this change happened recently. This points me back to the tasks.


texts: When deleting a user do the entries they created also get deleted?

texts: We had an instance where a user deleted an admin and it seemed to delete the content that user had created. Is this currently how Craft works? If so is there a way around that without having to change every entry's author. Or suggestion adding a prompt to warn user of content being deleted and to just suspend them.


texts: What is the Pricing Structure for CraftCMS?

texts: Is the pricing listed on the site for the Pro & Commerce versions of CraftCMS a one time, per-site charge or a reoccurring charge (i.e. monthly, yearly)?


texts: After migration to staging, requesting any page other than Home results in 500 error

texts:
I've developed my site locally and now need to migrate to staging. The Home page is displaying correctly so I would assume that a database connection is not the issue. But requesting {staging_url}/{any_segment} results in a 500 Internal Server error.

Here I'm setting the environment in index.php:

if (substr($_SERVER['SERVER_NAME'], -strlen('.dev')) === '.dev') {
    define('CRAFT_ENVIRONMENT', 'development');
} else if ($_SERVER['SERVER_NAME'] == 'staging.blah.com') {
    define('CRAFT_ENVIRONMENT', 'staging');
} else {
    define('CRAFT_ENVIRONMENT', 'production');
}

Here's my general.php:

return array(
    '*' => array(
        'extraAllowedFileExtensions' => 'vcf',
        'omitScriptNameInUrls' => true,
    ),
    'development' => array(
        'devMode' => true,
        'siteUrl' => 'http://blah.dev',
        'environmentVariables' => array(
            'baseUrl' => 'http://blah.dev',
        ),
    ),
    'staging' => array(
        'siteUrl' => 'http://staging.blah.com',
        'environmentVariables' => array(
            'baseUrl' => 'http://staging.blah.com',
        ),
    ),
    'production' => array(
        'siteUrl' => 'http://blah.com',
        'environmentVariables' => array(
            'baseUrl' => 'http://blah.com',
        ),
    ),
);


texts: No fancy deployment, version control etc etc. Just a cut and dry walkthrough on how to get Craft CMS up and running on a LEMP stack, does it exist? I'm fairly new to craft but have had no problem with the more documented LAMP stack but there seems to be a lack of LEMP & specifically nginx directives relating to craft. Any help or advice would be greatly appreciated.


texts:
Anyone come across this problem with installing craft3 on windows with MAMP Pro.

I have installed composer and this seems to be working fine. The php path I added directs composer to C:/MAMP/bin/php/php7.1.20.

I can go through the install process but after clicking finish setup it gives me an install fail screen and says to check my logs.

In the MAMP php logs I get:

  PHP Warning: Module 'curl' already loaded in Unknown on line 0

  PHP Warning: Module 'openssl' already loaded in Unknown on line 0

I've tried unistalling composer and resetting the php path. Did not work.
I also added an ENV variable to the system for PHP pointing to the same path above.

I'm a little stumped with this now. So any help much appreciated.

Cheers


texts: Get entries with related to selected categories and then group by category

texts:
Background:

I have a listing overview page that lists teaching staff grouped by their department (A category group holds all departments). E.g.

All Staff Members:

-- Science --
    Mrs Magnesium
    Mr Bunson

 -- P.E --
    Mr Stretch
    Mrs Bend

-- Maths --
    Ms Multiplication
    Mr Trig

To achieve the above I am using this code, which is working perfectly on a single page:

{% set entries = craft.entries.section('staffMembers').with(['staffPhoto']).all() %}
{% for category, catEntries in entries | group('staffGroup.one().title') %}

    {% for entry in catEntries %}

{{ entry.staffTitle }}

{{ entry.staffBio }}

    {% endfor %}

{% endfor %}

Question:

The client now needs to split these staff members across different pages, like the example below. So in order to achieve this I want them to be able use a category field (entry.staffGroups) where they can select multiple categories (departments) to display on each page. Hope I am making sense!

Science Staff Page:

-- Science --
    Mrs Magnesium
    Mr Bunson

Physical Education Staff Page:

 -- P.E --
    Mr Stretch
    Mrs Bend

Mathematics Staff Page

-- Maths --
    Ms Multiplication
    Mr Trig

I am struggling to achieve this, my attempt is below:

{# get the selected categories (departments) from category field #}
{% set departments = entry.allDepartments.all() %}

{# Set the entries, and attempt to relate them to ONLY the selected departments.#}
{% set entries = craft.entries.section('staffMembers').relatedTo(departments|join(',')).with(['staffPhoto']).all() %}
    {% for category, catEntries in entries | group('staffGroup.one().title') %}

        {% for entry in catEntries %}

{{ entry.staffTitle }}

{{ entry.staffBio }}

        {% endfor %}

    {% endfor %}

Example of entry:

Thanks!!


texts: Next/Previous Asset or Image within Entry

texts:
I'm looking to create a way to navigate to the next/previous image in an entry's asset range and display only the current asset at one time(starting from first asset).

{% extends '_layout.html' %}

{% block main %}

    {{ entry.title }}

        Emily Ashcroft

    Commissions
    Portraits
    Personal
    Info

        {% for photo in entry.photos %}

  {% endfor %}

{% endblock %}

Click on left side of screen and the previous asset is displayed, click on the right and the next asset is output. I'm struggling to figure if I should use a method similar to paginating links to next/prev entries (but I don't think that would work for assets).

This code is taken from _entry.html page of a section.

Thanks for any help provided.


texts: Craft 3: how can I auto-redirect to a site version using the user IP?

texts:
I have set up multi-sites using several locales:

— International Website
    — English
— Local Website
    — French
    — Dutch
    — etc.

If the user has a French or Dutch IP, it should be auto-redirect to the Local Website version. Otherwise, it should be redirected to International Website.

I found this plugin, that probably could make this works: https://github.com/lukeyouell/craft3-geocookie. I guess I would need to check the cookie inside my base.twig layout before to finally {% redirect %} to the matching version?

But I was wondering if there were (better) other ways to do that?

Thanks!


texts: Using Preparse field to display matrix blocks in Control Panel, limitations?

texts:
I can successfully use the Preparse field type to display matrix fields in the control panel, however, the output is very limited. Even my  tag is stripped out.
Is there any way to do this short of writing a plug-in?
And if not, what is the simplest possible plug-in I could use as a base for this.
{% for thing in entry.myMatrixField%}
  {{ thing.item }} - {{ thing.amount|number_format(2, '.', ',') }}<br>
{% endfor %}


texts: How can I return the number of users registered after a specified date?

texts:
Ok little stuck on this. I am trying to return the number of users registered after a specific date. So far I have tried the below using after but it is still returning all users regardless of the date.

craft.users.status('active,pending').after('2015-06-22').total()

Any help appreciated.


texts:
I tried up update to the latest Craft, but assets are not loading and the process stops here.

I deleted the storage/runtime folder but I got no luck.

Log says:

2016/11/08 20:17:23 [error] [application] Tried to read the folder contents of /var/www/dev/craft/craft/storage/runtime/compiled_templates/, but could not.

It doesn't matter if I set it to 777 or correct user.

Even stranger is that dispite the error log, I get content created in the compiled_templates folder.


texts: Stuck when grouping entries to get any other parameters like url, id etc

texts:
So I am trying to group entries by location and then group entries in this group by weekday.
I have this aspect working with the following code:

{% set allClasses = craft.entries
  .section('tuitionClasses')
  .relatedTo({
  targetElement: entry,
  field: 'tuitionCourse'
})
  .all() %}

{% set allEntriesByLocation = allClasses|group(e => e.location.one.title) %}

    {% for location, entriesInLocation in allEntriesByLocation %}

        <button
          class="focus:outline-none p-4 px-6"
          :class="{ 'text-pink-600': tab === '{{ loop.index }}' }"
          @click="tab = '{{ loop.index }}'"
        >

{{ location }}

        </button>

    {% endfor %}

  {% for location, entriesInLocation in allEntriesByLocation %}

      {#
{{ location }}
#}

      {% set locEntriesByWeekday = entriesInLocation|group(i => i.weekday) %}

        {% for weekday, entriesForWeekday in locEntriesByWeekday %}

{{ weekday }}

              {% for class in entriesForWeekday %}

                  {{ svg('@icons/bx/bx-time.svg', class="w-5 h-5 mr-1 flex-shrink-0 fill-current") }}
                  {{ class.classTime.one.title }}

              {% endfor %}

        {% endfor %}

        <button
          @click="html='loading...'; showLoading = true; showModal = !showModal;
              fetch('{{ entry.url }}', {
                method: 'GET',
                headers: {
                'X-Requested-With': 'XMLHttpRequest',
                },
              })
              .then(response => response.text())
                .then(text => {
                html = text
                showLoading = false;
              })"
          class="flex items-center justify-end text-left"
        >

            {{ svg('@icons/bx-solid/bxs-map.svg', class="p-px w-full h-full flex-shrink-0 fill-current") }}

            {{ location.url() }}

              Map and Directions

        </button>

However, where I am stuck is accessing the url for the locations.
I have a button that should load the location page into a modal when clicked.

However, when I try {{ location.url() }} I get the following error.

Impossible to invoke a method ("url") on a string variable ("Hatch End").

So How can I get any other element details of the location via this approach?
Or is there a different approach I need to take?

Thanks.


texts:
if that entry is in a particular section, then I want to do some task.

I can't really find the event docs I need to do that. Everything I've come across has been for Craft 2.

Any steps for a hint?


texts: Import Stripe subscriptions into Commerce 3

texts:
Is there a straight-forward way to import Stripe subscriptions into Commerce 3? I had hoped FeedMe or similar would do it, but it seems not: https://github.com/craftcms/feed-me/issues/472

Any help/advice greatly appreciated.


texts: Create custom field to input canonical url in a page

texts:
What is the best way of creating a custom field for each page whereby the user can input a URL into a field, which then gets input into a rel=canonical element like the example below.

<link rel="canonical" href="{{URL_FROM_CUSTOM_FIELD}}">

I already have an SEO tab like in the image below, however I am unsure of how to create a custom field inside this tab.

If someone could point me in the right direction, that would be great, as I am very new to the CMS.


texts: Template for Site Group rather than site handle

texts:
We are building a multi-site set up in Craft. We will have a lot of "microsites" for different locations.

I have a site group called "Microsites" and I would like the home page for each of these sites to load a template inside /templates/microsites/index.twig

I don't want to create individual folders in the template folder for each site.

Is this possible?

Edit: I'll provide overview of the site setup

So I will have over 100 different sites on here representing a location. We have a Locations channel on the main site that will hold the data we will query in the Microsite template.

Each microsite will have its own base URL like so:

@web/san-francisco

so whenever that page is loaded, I want it to go into /templates/microsite/_index.twig

Every single microsite home page will use that same template and have the data be loaded dynamically.

The reason we can't just use Channel entries is because we will need localized blogs for them.

Maybe I'm going about this all wrong?


texts:
I'm trying to update all my project plugins. Over a year ago I originally installed Sprout Forms beta as a trial and have since purchased the license.
When I run craft update I get

Your requirements could not be resolved to an installable set of packages.
Problem 1

barrelstrength/sprout-forms-range-slider 1.0.5 requires barrelstrength/sprout-forms ^3.0.0-beta.47 -> satisfiable by barrelstrength/sprout-forms[v3.x-dev].

barrelstrength/sprout-forms-range-slider 1.0.5 requires barrelstrength/sprout-forms ^3.0.0-beta.47 -> satisfiable by barrelstrength/sprout-forms[v3.x-dev].

Conclusion: don't install barrelstrength/sprout-forms v3.x-dev

Installation request for barrelstrength/sprout-forms-range-slider 1.0.5 -> satisfiable by barrelstrength/sprout-forms-range-slider[1.0.5].

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

I get this (or similar) message often. I want to resolve it once and for all. Do I just uninstall Sprout Forms beta? Someone reassure me I won't lose all my data.


texts: What needs updating when moving site from subdomain to root?

texts:
I've just moved a site from a subdomain to the root.

So far I've updated the index.php file and also the settings in the control panel

System->General->SiteUrl

to reflect the new path of the craft directory and index.php relationship.

I can access the admin backend but the actual site gives the craft styled "Page not found."


texts: Installing happylager demo site on own server (not locally)

texts:
I would like to install the happylager demo site on my server instead of installing it locally,
but all i get is 404 pages when i visit http://adamridovics.com/happylager.dev/admin
Is this possible at all, or i am doing something worong?


texts: Formerly - Checking if e-mail already entered

texts:
So, I have a form created using formerly and their template.

The form works fine, but I am trying to check for duplicate e-mails and just stop a submission when it notices there is one in the system. The following works and the console spits out true on data.alreadysubmitted but the line below does not stop the post. How should I handle this?

(I know the code needs cleanup. It will be done after functionality is met. I still need to check date of submission after finding an email duplicate to enable a 1 entry per day style form)

$("#form").on('submit', function (e) {
        console.log($("#formtest_email").val());
        $.post('?ok=1', {
            action: 'formerly/submissions/alreadySubmitted',
            formid: $("input[name=formId]").val(),
            email: $("#formtest_email").val()
        },
        function(data, status){
            console.log("already?:" + data.alreadysubmitted + "\nStatus: " + data.ok);
            if (data.alreadysubmitted == true)
            {
                 e.preventDefault();
            }
        });
});

Update: After trying to store data.alreadysubmitted outside of the function, I realize that the function executes after anything below it (outside of the whole .post method). Would it be right to assume that the function is called after the submit is complete, and hence e.preventDefault will not work?


texts:
I want to change a few words in the CP (Craft 3). What's the best way to do it, without being overwritten by a Craft update if possible...?
I was thinking about creating my own language file, but can't find the complete method to do so, and it might still be affected by an update? Any ideas?


texts: Using Amazon S3 with Craft 2.x in Frankfurt region

texts: According to this post it's not possible to use Craft 2.x with Amazon S3 within the Frankfurt region. As Craft 3 is still not near release it would be nice to have some sort of a fallback solution. For us that issue is a major drawback ... and I can imagine for other folks from the EU region too.


texts:
I like the setting autoLoginAfterAccountActivation. Is there something similar to log in users after a password reset?

I can approximate this by using the users.onSetPassword event, confirming the user isn't already logged in (i.e. using a normal set password form), and confirming that the user model doesn't have an unverifiedEmail value (i.e. is a brand new user), and then using craft->userSession->loginByUserId() but this seems like a very roundabout and potentially stupid way to do this.


texts: Adding second user to user field in plugin brings server to its knees

texts:
I'm building a plugin which needs to add users to a users-type field when they edit the entry on the front-end. It works well when the post is created, adding the original author to the field, and again when the same user edits the post. However, when another user edits the post everything comes to a standstill for a minute and users are taken not to the landing page, but to a page containing nothing other than a "1". Checking the back-end, it has added the second user to the field, though.

Can anyone suggest to me from the code below why adding a second (haven't tested any more than that yet) user brings things the server to its knees?

public function init()
{
    parent::init();

    // ON SAVE ENTRY
    craft()->on('entries.saveEntry', function(Event $event) {

        $entry = $event->params['entry'];
        $user = craft()->userSession->getUser();
        $notifyMe = craft()->request->getPost('notifyme');

        // CHECK THIS IS THE FORUM SECTION
        if ($entry->sectionId == 16) {
            craft()->notifier->addAnotherUserToNotify($entry, $user, $notifyMe);
        }
    });
}

And here is the function:

// ADD ANOTHER USER TO A POST'S NOTIFICATION LIST
public function addAnotherUserToNotify($entry, $user, $notifyMe)
{
    if ($notifyMe == "yes") {

        // GET IDs OF USERS ALREADY LISTED TO BE NOTIFIED
        $usersToNotify = $entry->usersToNotify->ids();
        if ( ! in_array( $user->id, $usersToNotify ) ) {
            // ADD THE CURRENT USER TO THE ARRAY OF USERS TO BE NOTIFIED
            $usersToNotify[] = $user->id;
        }

        // UPDATE THE ENTRY'S FIELD WITH THIS UPDATED ARRAY
        $entry->getContent()->setAttribute('usersToNotify', $usersToNotify);

        // SAVE ENTRY
        craft()->entries->saveEntry($entry);

    }

}

The code is inspired by Update User "Field Type" for Entry in Plugin


texts: Set Variables from the Matrix Field - SEO

texts:
quick question.

{% for block in entry.matrix %}
    {% if block.type == "seo" %}
    {% set descr = block.metaDescription %}
    {% endif %}
{% endfor %}

{% if descr is defined %}
    <meta name="description" content="{{ descr }}" />
{% endif %}

meta description won't show up? what am I doing wrong?


texts:
Installing Craft 2.2 succeeded. But every main content in the admin is hidden. Example Dashboard (copy & paste from ff debug, which shows only containers without sub nodes!):

 <---- display: none

 <---- display: none

 <---- display: none

 <---- display: none

 <---- display: none

When display: none is disabled in FireDebug I see evreything how it should.

What is wrong?


texts: When you create a new user in the craft backend CMS, it used to be possible to set (and change for existing users) the password.  It appears recently (last 6 months+) that this feature has been removed, is there a simple way to re-instate this feature or is the only way to set the password the password re-set url feature?


texts: P/T ContactForm Retrieving Custom fields Value after submitting form

texts:
I'm trying to retrieve custom fields value after submitting a form. Trying to access the custom fields through the message element after the form is submitted always throws an error  that the custom fields variable does not exist.

Example that works:

Name:*
<input id="fromName" type="text" name="fromName" value="{% if message is defined %}{{ message.fromName }}{% endif %}">`

Example that doesn't work (custom fields):

Company:
<input id="fromCompany" type="text" name="message[fromCompany]" value="{% if message is defined %}{{ message.fromCompany }}{% endif %}">

Is it possible to retrieve custom field values after submitting the form?


texts:
I'm trying to send a sprout email from my plugin like so:

use barrelstrength\sproutbaseemail\mailers\DefaultMailer;
use barrelstrength\sproutbaseemail\SproutBaseEmail;
use barrelstrength\sproutbaseemail\elements\NotificationEmail;

use Craft;
use craft\base\Plugin;

use yii\base\Event;

class MyPlugin extends Plugin
{
    public function init()
    {
        $mailer = SproutBaseEmail::$app->mailers->getMailerByName(DefaultMailer::class);

        // How do I let it know what email to send?
        $mailer->sendNotificationEmail();
    }
}

It says that sendNotificationEmail expects an instance of NotificationEmail but I can't seem to find any documentation on how to reference the notification email created on the dashboard so it can be sent.

The only similar question I found was this but it's for Craft2.


texts: Execute code before plugins are executed

texts:
I'm looking for a way to execute some code before the whole system loads, more precisely right before plugins are loaded/executed.

Use case

I want to instanciate a custom object, that I need to interact with in my plugin, but I cannot declare it INSIDE my plugin. This object should actually be available in all plugins if needed.

Where should I put such code so it is reusable ?
Thanks a lot !


texts: How can I upgrade to version 3.0 as a user?

texts: I am an end user and see there is a 3.0 version. Can I upgrade for free and what steps do I need to take to do that?


texts: How do you tell Craft to change post directions from row-to-row?

texts:
I have a grid.  The pattern is:

**Row 1** = 1 x featured post and 2 x vertical posts.  (The feature is the equivalent of 2 vertical posts.)
**Row 2** = 2 x horizontal posts  Row 2 starts with the 4th most recent post.
**Row 3** = 4 x vertical posts
**Rows 4-n** repeat Row 2 and Row 3...

I have experimented with {% if loop.index is divisible by(2) %}stuff{% else %}other-stuff{% endif %} to switch between the horizontal and vertical alignments.

So, this is a 2 part question.

How do I pull the 2nd and 3rd most recent posts to populate the 2 vertical posts in Row 1?

I am already calling the featured post using {% for post in craft.entries.section('posts') %}{% if loop.first and craft.request.pageNum == 1 %}...

Next, how do I then tell Craft to populate 2 horizontals in Row 2 and then switch to 4 verticals in Row 3?   I assume its best to separate step #1 from step #2 which would require Row 2 to start with 4th most recent post


texts: getting redactor video.js plugin installed

texts:
I tried to install the redactor video.js plugin but I can't make it work. I tried to intgrate it via "control panel js" plugin. Put the "video" tag under "buttons", but it doesn't appear. How do I integrate the video.js plugin properly?
Craft 3.5.13.2, Redactor 2.8.2


texts: How do you query entries by field values?

texts:
I need to arbitrarily query entries based on the values of various fields.

For example, if I have an entry type called "Widgets" I can grab them like this:

$widgets = Entry::find()->section('widget')->all();

Now what if widgets have a field called "widgetColor" and I want to select all with a value of "blue" in that field?

How can I query for those entries?
Also, how can I query for any entry with no value in that field?

I've tried my best to figure it out using the documentation and it seems like method such as where only apply to certain data, such as the title and slug, which are not custom fields on the entry type.

Thanks!


texts: Check if a table field’s column has a value

texts:
I am using a table field to display credits on a portfolio page.
The table field has three columns: hva, hvem and url.

The url should be optional and I want to set up an if statement showing it as a link if it has a value. Is this possible using the table field?

Also, the table field can have multiple rows.

I have tried to set up an if for row.url to see if has a value. And an else for when there is no URL.

{% if entry.credits|length %}
    {% for row in entry.credits %}
        {% if row.url == 0 %}

{{ row.hva }}: {{ row.hvem }}

        {% else %}

{{ row.hva }}: {{ row.hvem }}

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


texts:
I am playing around with Craft 3 and for the life of me cannot get it to save an element programmatically.

I am trying to save a Global Set from a module like so:

$config = [
    'name' => "My New Global Set",
    'handle' => "mfSet2",
];

$glob = new \craft\elements\GlobalSet($config);

$success = Craft::$app->getGlobals()->saveSet($glob);

$success returns true and there are no errors. But nothing is saved. There doesn't seem to be any documentation that helps and searching just turns up Craft 2 examples.


texts:
I'd like to only load some scripts for 1 specific page with the Url /projects/.
Currently I'm using:
{% if craft.app.request.segments|first == 'projects' %}
 // load scripts
{% endif %}

This works.
However, I also have pages with the Url /projects/project-name which should not load the script.
How can you perform a conditional test for just the Url /projects/ ?
Thanks


texts: Filtering entries by multiple URL parameters on the front end

texts:
This answer here helped me get multiple same-name parameters to filter entries:
(ex: ?recipe=healthy&recipe=salad&recipe=dinner)

Now I'm looking for a way to get multiple different parameters to help sort entries on the front-end. Something like:
?collection=healthy&ingredient=salad&meal=dinner

The code I have now is this (pretty much verbatim what came from the answer linked above):

{# Get search parameters from the URL query string #}
{% set collectionQuery = craft.request.getParam('collection') %}

{# Start an array of search parameters (relationParam) with 'and' to match ALL categories #}
{% set relationParam = ['and'] %}

{# Find categories that match the slugs in your query string... #}
{% for querySlug in collectionQuery %}
  {% set collectionCategory = craft.categories.group('recipes').slug(querySlug) %}

  {# And merge them into the relationParam array. #}
  {% set relationParam = relationParam|merge({targetElement: collectionCategory}) %}
{% endfor %}

{# Avoid passing an array with `['and']` only #}
{% if relationParam|length < 2 %}
  {% set relationParam = '' %}
{% endif %}

{% set searchParams = {
  relatedTo:  relationParam,
  section: 'generalContent',
  type: 'recipes'
} %}

<form action="/recipes">
  {% for category in craft.categories.group('recipes').level('1') %}
    <div style="display: inline-block;">
    <select name="{{ category.slug }}[]" onchange="this.form.submit()">
      <option name="{{ category.slug }}[]" value="">Any {{ category.title }}</option>

      {% for categoryChild in category.children() %}
        <option name="{{ category.slug }}[]" value="{{ categoryChild.slug }}"{{ categoryChild.slug in collectionQuery  ? 'selected'}}>{{ categoryChild.title }}</option>
      {% endfor %}
    </select>
    </div>
  {% endfor %}
</form>

{% paginate craft.entries(searchParams) as entries %}
    ...
{% endpaginate %}


texts:
I need to displaying some notifications on a Craft site, and I want to allow users to mark each notification as read. There won't be many users or notifications, so a plugin seems overkill. Instead I've created a Notifications section with a Read by (Users) field called notificationReadBy.

Notifications display on the template inside an entry form, with a hidden multi-select field containing all users who've marked the notification as read (i.e. already submitted the form) plus the current user's id in case they want to mark as read too. That works fine to build a list of users who've already read the notification.

Next step is to hide the notification altogether if the current user has already marked it as read, and is listed in the Read by field. So I thought something like this might work...

{% for entry in craft.entries
    .section('notifications')
    .all() %}
    {% set readBy = entry.notificationReadBy %}
    {% if currentUser.id not in readBy %}
        {# Show the notification #}
    {% endif %}{% endfor %}

Does that make sense? Anyway, it's not working as expected and is displaying the entry regardless of whether the current user is listed in Read by or not. Any ideas? Maybe it's neater to move the query up to the entries tag, using the .search() param, but I can't get that working either?


texts: Element API plugin: searching and working with nested objects

texts:
I’m experimenting with the Element API plugin and working with querying the tags of the assets that appear in matrix blocks in a set of entries. Essentially I’m hoping to be able to use a tag in a query string to return a list of entries where any asset with that tag appears. I’ve gotten as far as returning all of the information I need, but I’m having trouble figuring out how (or whether I can?) use a search function GET request to retrieve the list of entries I need.

Here is where I am:

'endpoints' => [
    'api/projects.json' => [
        'elementType' => Entry::class,
        'pretty' => true,
        'criteria' => [
            'section' => 'projects',
            'type' => 'projectDetail',
        ],
        'transformer' => function(Entry $entry) {
            $relatedAssets = [];
            foreach ($entry->projectDetailMatrix as $block) {
                $image = '';
                $id = '';
                $tags = [];
                $asset = $block->imageSelection[0];
                if (!is_null($block->imageSelection)) {
                    $image = $asset->getUrl();
                    $id = $asset->id;
                    foreach ($asset->tags as $tag) {
                        $tags[] = $tag->slug;
                    }
                    $relatedAssets[] = [
                        'assetUrl' => $image,
                        'assetId' => $id,
                        'assetTags' => $tags
                    ];
                }
            }
            return [
                'title' => $entry->title,
                'url' => $entry->url,
                'relatedAssets' => $relatedAssets,
            ];
        },
    ],
]

And here's what I get:

{
    "data": [
        {
            "title": "Project1",
            "url": "http://site.dev/project1",
            "relatedAssets": [
                {
                    "assetUrl": "//site.dev/uploads/image1.png",
                    "assetId": "12",
                    "assetTags": [
                        "red",
                        "dark"
                    ]
                },
                {
                    "assetUrl": "//site.dev/uploads/image2.png",
                    "assetId": "13",
                    "assetTags": [
                        "red"
                    ]
                }
            ]
        },
        {
            "title": "Project2",
            "url": "http://site.dev/project2",
            "relatedAssets": [
                {
                    "assetUrl": "//site.dev/uploads/image3.jpg",
                    "assetId": "14",
                    "assetTags": [
                        "blue",
                        "dark"
                    ]
                },
            ]
        }
    ]
}

So my end goal would be

/api/projects.json?t=dark

returning the Project entries whose matrix content includes an asset with the tag "dark". Is this possible, or too much of a rabbit hole at this point? Any pointers appreciated!


texts: Static translations not working on Craft 3 since upgrade from Craft 2

texts:
I have upgraded from Craft2 to Craft3 and static translations no longer seem to work.

I have created a folder at the same level as the "vendor" folder called "translations" and have got a folder inside that called "en_us" (base language is en_gb). Inside that folder we have a file called "site.php" and inside that is the following:

<?php

return [
    '£' => '$',
    'USD' => '$',
];

The static translation page (https://docs.craftcms.com/v3/static-translations.html) says: "..To do that, create a new folder in your project’s base directory called translations/, and within that, create a new folder named after the target language’s ID".

I assume that is a typo, but I have tried naming the folder the ID number of the site...

I've also tried renaming the folder to "en-US", "en-us" but nothing seems to work.

Code example for a translation attempt in a template: {{ "£" | t }}.

Any help very gratefully received!


texts: How do I format the date and time I got from an entry?

texts:
I am working on a project where the content manager can add events (entries). These events have a date, starting time and end time. The fields in the cms show the option for adding a date, time and time accordingly.

To print them in HTML I do this.

Date

{{entry.datum}}

Starttime

{{entry.begintijd}}

Endtime

{{entry.eindtijd}}

However, only the date is shown, like this:

2014-11-30

2014-11-30

2014-11-30

How do I format the result so I get the times in a format like 15:00?

Also, how do I format the date to be shown in Dutch time format, like 1 januari 2015?

Thanks in advance


texts:
I want to display some content only if a user from a certain group (wholesalers) is currently logged-in. The following syntax seems to work - but is there something more shorthand than the nested conditionals I'm using?

{% if currentUser %}
    {% if currentUser.isInGroup('wholesalers') %}
        Do something here...
    {% endif %}
{% endif %}


texts: Display variant title on cart page only for items with more than one variant

texts:
I want to display the variant title only on line items which have more than one variant.

On the Image you can see the bold Product title and undeneath there is the variant title (Format A2). As you can see the last line item has only one variant so it's unnecessary to show the title there twice.

How do I write the conditional to show the title only on products with more than one variant?

On the Product page I just wrote it like this:

{% if product.variants | length > '1' %}
  {% for purchasable in product.variants %}
     {{ purchasable.title }}
  {% endfor %}
{% endif %}

But in the cart it's a line item and not a product so this code doesn't work. How do I have to apply this to a line item?


texts: Does normal authentication occur before userSession.onBeforeLogin event?

texts:
I'm trying to take advantage of the userSession.onBeforeLogin event to interrupt the normal Control Panel login (/admin/login) so that I can first authenticate the user against an LDAP server. However, in my testing it seems that Craft runs its own authentication prior to onBeforeLogin event.

class AdminAuthPlugin extends BasePlugin
{
    public function init()
    {
        parent::init();

        craft()->on('userSession.BeforeLogin', function (Event $event) {
            if (craft()->request->isCpRequest() == true) {
                $event->performAction = false;
                exit();
            }
        });
    }
}

Using the above example, attempting to log in with a known username (with correct password) who has access to the CP, UserSessionService throws an error--which I expect to see due to the exit(): "An unknown error occurred." However, if I try to log in with the same username and an invalid password, UserSessionService throws the standard error, "Invalid username or password", which indicates that onBeforeLogin has not been executed.

Am I correct to understand that the userSession.onBeforeLogin event indeed fires after the default authentication attempt?


texts: Visiting any locale gives the same locale output

texts:
The site has 5 locales targeting 'en_gb', 'fr_fr', 'de_de', 'it_it', 'es_es'.
When I'm at site.com it gets current locale correctly en_gb. When I visit site.com/fr/ locale, It loads blank page with current locale en_gb. The same scenario repeats for all locales, except the top level local en_gb.

I went through my settings multiple times, but I still wasn't able to find a problem.

My general.php settings:

return array(

// Local environment
'site.craft.dev' => array(
    'devMode' => true,
    'environmentVariables' => array(
        'sitePath' => '/OS/Applications/MAMP/sites/site.craft.dev/public/',
        'siteUrl' => 'http://site.craft.dev/'
        ),
    'siteUrl' =>  array(
        'en_gb' => 'http://site.craft.dev/',
        'fr_fr' => 'http://site.craft.dev/fr/',
        'de_de' => 'http://site.craft.dev/de/',
        'it_it' => 'http://site.craft.dev/it/',
        'es_es' => 'http://site.craft.dev/es/',
        ),
    )
);

Public folders are structured  and set according to documentation, named after locale's handles like that: fr_fr, de_de etc.

and with $craftPath variable set to necessary handle like fr_fr, de_de etc.

When I visit site.craft.dev/fr/ and ask for current locale by {{ craft.i18n.getCurrentLocale() }}, it gives me default locale en_gb.


texts:
I've downloaded craft 3 on Windows 10 using XAMP but everytime i try to install craft it skips the first step and it always put me at the second step of the install
After I fill the forms for install I get "Install failed please check logs for more info".
I also get "The info table is missing its row in C:\xampp\htdocs\crafty\vendor\craftcms\cms\src\base\ApplicationTrait.php:512"

I've checked on phpmyadmin and all the rows are empty but they are created.

Seems that running the setup from shell fixed the problem


texts: Mark a Commerce Order as Paid, via a custom plugin

texts:
Checkout / Payment is being handled entirely by a 3rd Party. What would be the correct process to mark an Order as Paid via a custom Craft plugin?

The Order will already have been converted from a Cart to an Order and assigned an Order Status via a previous step.

The 3rd Party will be calling a series of API endpoints exposed by a custom Craft plugin to process the various steps of the Order.

EDIT: For future reference, base on Luke's answer below, this is the code I got to work...

$orderNumber = "XXXX-XXXX-XXXX-XXXX";

$order = craft()->commerce_orders->getOrderByNumber($orderNumber);

$transaction = craft()->commerce_transactions->createTransaction($order);

$transaction->status = Commerce_TransactionRecord::STATUS_SUCCESS;
$transaction->type = Commerce_TransactionRecord::TYPE_PURCHASE;

craft()->commerce_transactions->saveTransaction($transaction);

craft()->commerce_orders->updateOrderPaidTotal($order);


texts:
I've using a matrix field from the same entry in two different templates. In one template I want them in the order they're displaying in the CMS, while in the other I want them displayed in reverse.

It doesn't like this:

{% for cta in entry.ctas.order('desc') %}

Can this be done any other way?


texts: Updating user email does not update username when useEmailAsUsername is set

texts:
When the config setting useEmailAsUsername is set, I would expect updating a users' email address to also update the username field when saving the element. However, this does not occur unless you manually call php craft utils/update-usernames.
Should the username be updated when a users' email address is updated?
Is there a method to trigger this for the current user via a plugin or do I just need to update username alongside email?
Version: 3.5.15.1
Edit: This also prevents registration of a new user with the previous email address but does not indicate what the problem is clearly.


texts: How do I retrieve tags and tag data for an entry in Element API?

texts:
In Element API v1, I am setting up an endpoint that is trying to expose a news entry including the tags (title, id, slug) associated with it. Thought it could be set up similarly to how you can retrieve categories using an array_map. But my code doesn't seem to work for tags.

'api/news.json' => [
  'elementType' => ElementType::Entry,
  'criteria' => ['section' => 'news'],
  'transformer' => function(EntryModel $entry) {
    return [

      'id' => $entry->id,
      'title' => $entry->title,
      'slug' => $entry->slug,
      'postDate' => $entry->postDate,
      'url' => $entry->url,
      'jsonUrl' => UrlHelper::getUrl("api/news/{$entry->id}.json"),
      'description' => (string) $entry->newsDescription,
      'tags' => array_map( function(TagModel $tag) {
        return [
          'id' => $tag->id,
          'title' => $tag->title,
          'slug' => $tag->slug,
        ];
      }, $entry->newsTags->find()),
      'type' => array_map( function(CategoryModel $category) {
        return [
          'id' => $category->id,
          'title' => $category->title,
          'slug' => $category->slug,
        ];
      }, $entry->newsType->find()),

    ];
  },
],


texts:
By default, if we use cyrillic in the names of entries, the slug is also created in сyrillic. This is not good. And here we need transliteration such as б → b, д → d, etc.
By the way, if we create for example a new section in сyrillic, the handle, Entry URI Format and Template is created almost correctly, the exception is the characters 'Ь' and 'Ъ' - they are replaced by a space.

Ok, in general.php add
'limitAutoSlugsToAscii' => true

to replace characters according to ASCII character mapping. Now slug in entries should be created correctly, but again a new problem with the characters 'Ь' and 'Ъ', they are not converted.

in general.php add
'customAsciiCharMappings' => [
    ' ' => ['ь', 'Ь', 'ъ', 'Ъ'],
],

and we get the same result as when creating a new section - space.
Tried this variant:
'customAsciiCharMappings' => [
    '' => ['ь', 'Ь', 'ъ', 'Ъ'],
],

does not work
In the correct convertation there should be no spaces or replacement, 'Ь' and 'Ъ' should be removed (Мальчик → malchik). How to remove these spaces?


texts: Can I force extra fields to be required on asset upload

texts:
I am trying to figure out if there is a way to require additional fields be filled out while uploading an asset (mainly pdf's) in the admin control panel.  I know I can add meta data fields to an asset but the process seems to be upload the asset and then edit the assets to fill out those fields.  I could easily see a user uploading and not filling out the fields and for my requirements I need those fields to be filled out.

I am guessing I will have to create a plugin to handle this functionality but wanted to check if I am heading down the right path and if it is even possible.

Thanks


texts: Populating a Custom Field via a Plan Choice in Charge?

texts:
We are using Charge and have two custom fields we want to populate when a charge is successful. One works and one doesn't.

We can get it to populate a "pageTitle" field which is pretty standard as a hidden field.

The other field's value needs to change based on the selected planChoice - this one doesn't save anything. The Charge works but the custom field remains blank. Any ideas how to get this to work?

Here's stripped down code:

<form ...>
    ... charge specific default stuff ...

    <input type="hidden" name="fields[pageTitle]" value="{{ entry.title | e }}"/><!-- This is a custom field on the Charge, that does get saved -->

    {% set options = {
        'planChoices' : {
            'two' : {
                'label' : "This is a standard Charge field #{entry.title}",
                'planAmount' : (ticketPrice * 2),
                'fields[ticketInfo]' : "This is a custom field on Charge that doesn't get saved #{entry.title}"
             },
             ...
         }
    } %}

    {{ craft.charge.setPaymentOptions(options) }}

    {{ forms.select({
        label:   'Plan Choice',
        name:    'planChoice',
        id:      'planChoice',
        options: options.planChoices,
        value:   (charge is defined ? charge.planChoice),
        errors:  (charge is defined ? charge.getErrors('planChoice'))
    }) }}

    ... other normal form bits ...
</form>


texts: How do I stop my relative links to stylesheets breaking?

texts:
When I navigate to [home]/news/2014/poster my relative links to stylesheets break. I am using:

<link href="css/myStylesheet.css" rel="stylesheet">

How do I stop these links breaking in this scenario?


texts:
I need to add and/or change an attribute in the order table on /admin/commerce/orders.

The Order Element itself does not have a EVENT_SET_TABLE_ATTRIBUTE_HTML, and I've tried with variations like this:

public function init()
{
    parent::init();
    Event::on(Element::class, Element::EVENT_SET_TABLE_ATTRIBUTE_HTML,[$this, 'setOrderStatusTableAttributeHtml']);
}

public function setOrderStatusTableAttributeHtml($event, $attribute)
{
    if ($event->element instanceof \craft\commerce\elements\Order && $attribute == 'orderStatus') {
        return 'Changed';
    }
}

The event does not show up in the debug bar. I've also tried a EVENT_INIT with die('died') an that kills the execution, so my plugin is installed and loading.


texts:
I've built a site using Craft, and now, I'd like to be able to create a mirrored development environment. With that, I'd like to be able to make changes and edits to the website that can then be pushed to the main site. I know that craft has these features built in, but I have not been able to understand exactly how to get it to work. Is there someone wonderful on here that can explain how to get it done, or could include a link to another thread that explains?

Thanks in advance!


texts: How can I create a Module/Plugin to edit multiple entries via a single front-end form in Craft 3?

texts:
Scenario:

I have a Structure section called Competitions that allows users to submit one or more (usually three maximum) entries to judged photo competitions. However, they can only submit one or two if they wish.

Competitions (section)

Competition (parent entry type)

Submission (child entry type)

The Submission entry type's field that the users need to edit are:

Image order: a number field that is chosen from a radio button group. The number of buttons in the group corresponds to the number of entries the user has submitted. This is usually max 3. If I have the following order: Image 01, image 02, & image 03, and the user deletes image 02, image 03's order needs to change to 02.
Critique image: a ligthswitch field in a single radio button. They can only select one image for critique.

There's also an asset field for an image. This needs to be renamed according to the chosen image order. E.g: 01-compId-dateTime.jpg. I have this part working via a Craft 3 Module.

Here's an annotated screenshot to illustrate: https://cl.ly/ba29ed3cfc19

I tried to do this via Javascript (Vue.js), but it breaks when an entry is deleted. In the end, it's just not robust enough, and I prefer having a single save button that sends all form data to the server. Here's that attempt: How can I edit multiple entries via multiple front-end forms using Vue.js?

I found this post How do I create a plugin to create and save multiple entries from one front-end form?, but the answer isn't detailed enough for my current skill level, and it's for Craft 2. Same with this: Edit multiple entries at once through the front-end. The answer at Entry Form - Multiple Entries & Entry Type & Parent contains the detail I need, but it's for Craft 2.

Many thanks for your help.


texts: Can someone explain to me the difference between 'not' and without?

texts:
Here is an example of code I'm trying to use to eliminating have to iterate comparing the current entry.title to the related to entry.title then omitting it.

{% set entries = craft.entries.relatedTo(context).limit(MAX_FILLERS).id('not' ~ entry.id) %}

{% set entries = craft.entries.relatedTo(context).limit(MAX_FILLERS)|without(entry.id) %}

Current code I'm trying to get around with a single relatedTo call.

{% set entriesUnfiltered = craft.entries.relatedTo(context).limit(MAX_FILLERS).search('-title:'+entry.title) %}

{% set entries = [] %}

{# Removing self entries #}
{% for e in entriesUnfiltered%}
    {% if e.title not in entry %}
        {% set entries = entries|merge([e]) %}
    {% endif %}
{% endfor %}


texts: Updated the PHP on server. Getting this error: Please ensure that $craftPath is set correctly

texts:
I am running Amazon Ec2 instance and tried updating the PHP on the site using this guide: http://brianshim.com/webtricks/update-amazon-ami-php5-3-to-php5-4/

And now this is the error I am receiving:
Please ensure that $craftPath is set correctly in /var/www/html/staging/public/index.php

I tried resetting the permissions, and restored the old http config files, to no avail. I have no idea what it could be. I checked php.ini for open_basedir and did not find it.

Could it be the permissions?


texts:
Hello I have a website built in Craft 3. I have some components built in React but typically the site is served using Twig templates.

How can I make an axios call to craft to request the page's entry blocks, sections, etc? Is this possible?


texts:
I've recently setup a new cloud server for a client with a Craft Multi Environment setup. And I also would like to to be able to do the Database & Asset Syncing Between Environments in Craft CMS as in the excellent nystudio107 article.

I have it setup at my work and it works really well as you just have to navigate to /scripts folder via the terminal, and then type ./pull_db.sh

Like I said I have this setup at my office and it works really well. But on this new server I've setup I'm having an issue in that I get the following when I do the ./pull_db.sh

-bash: ./pull_db.sh: Permission denied

I've checked the setting in the .env.sh that I've created and match what I have in the office setup. So need to work out why I'm getting the permission denied.

Anyone got any ideas?


texts: Trouble generating correct srcset sizes using getSrcset()

texts:
I'm trying to figure out the getSrcset() method, going by the docs here.
When I try it using the code in that example (I modified to account for a Matrix field but other than that it is the code below), the results aren't what I'd expect. It takes the asset and INCREASES the sizes; what I would expect is the uploaded asset is considered the maximum resolution, and it is DECREASED from there.
Here is the code from that example page:
{% do asset.setTransform({ width: 300, height: 300 }) %}
{{ tag('img', {
    src: asset.url,
    width: asset.width,
    height: asset.height,
    srcset: asset.getSrcset(['1.5x', '2x', '3x']),
    alt: asset.title,
}) }}

Basically I can't figure out how to tell it to scale down, not up.
I'm also not clear on what that first line is doing (width: 300, height:300) because it doesn't set my images to those sizes.
Edit
Just to clarify, I know you can pass in actual sizes instead of x-descriptors, but what I can't figure out is how you can use the x-descriptors without ruining the image by scaling it up, which defeats the whole point of serving high-res images.
Update
I ended up just using Image Transforms, but I'd still be curious to hear if I was using the getSrcset() wrong and if there is a way to scale down instead of up.


texts: How to use promotable Boolean in Craft Commerce?

texts: I'm sure this is somewhere in Craft documentation but I cannot find anything on it. There is that checkbox in the product area that says "Promotable". I'm assuming this is so I can reference it later in the code (which is why I'm interested in this box), but I've browsed through the documentation and found nothing about it. The lack of questions about it on here makes me assume I just missed it. Could I get an explanation or a link? Thanks!


texts:
Can’t believe this is the first time I’ve had to do this, but I need to search a field inside a matrix and I can’t find any documentation on this. Craft 2 if that matters. I had hoped something like

  craft.entries.search('matrixField:field:value')

would work but doesn’t seem to. Anyone help me out?


texts:
The search ranking built into Craft orders site content searches by score...but that compromises the "exact match" searches that users might make for significant page titles that don't get searched for as often, but contain key words that are often searched. Is there a way around this? to allow the user to set the search by "exact match"? or to set the site to pick one or the other as its standard?

thanks,
Karin


texts: How possible is it to set write permissions on storage folder on symlinked install?

texts:
I have setup a site with a symlinked dir on nginx ubuntu server.

When I access the root of the site I get this:

/usr/share/nginx/html/releases/*********/craft/storage isn't writable by PHP. Please fix that.

In my structure I have a folder called current that gets symlinked to the new deployed site in releases and then current should point to that.

Can anyone shed some light on what might be happening here and how I can set the write permissions to the symlinked dir?

Thanks,
Mark


texts: Error when trying to change the database name

texts:
I get this error when trying to change a database name on a new dev with no entries:

What can be done?


texts: Redactor Richtext. Editing a Link with an "&" breaks the link

texts:
Both screenshots were done without saving the entry. Just adding the link inside redactor and opening the edit menu again.
Adding a new Link
After pressing add and edit the link again
You can see that the "&" is converted, but is still there. This breaks the second parameter inside the link. I tried disabling the HTML Purifier and all that good stuff but nothing worked for me.


texts:
I build a SPA with Craft CMS and Vue.
I use Vue Router and have three Props. Here is my current router-view:

<router-view
  csrfName="{{craft.app.config.general.csrfTokenName}}"
  csrfToken="{{craft.app.request.csrfToken}}"
  userID="{{currentUser.id}}"
/>

I build a user form which works perfect, but it would be great to get the loggedIn userID in the response or via GraphQL. With GraphQL we would have the advantage to check on every site if the user is still signed in

My log-in template looks the same like above but without the UserID. At the moment I make a hard redirect to my application with the userID because I can't get the data from GraphQL. That means I need to reload the whole page just to get the loggedIn userID. This isn't best practice.

Have someone a idea how I could solve this?


texts: Accessing Commerce product variant dimensions in the template

texts:
I have been unable to locate anything in the docs or any questions on here regarding how to print the dimensions associated with a variant in the template.

All I have managed to find is how to print the dimension unit using the following:

{% set dimensionUnits = craft.commerce.settings.dimensionUnits %}


texts: How to get first child URL within Craft/Twig Nav tags

texts:
I have a navigation structure as follows:

{% set page = entry ?? category ?? null %}

    {% nav entry in entries %}

            {{ entry.title }}

            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

    {% endnav %}

As you can see, I have an entry.type called "No link" which means that the user doesn't want the parent page to have a page of it's own, yet it still needs to appear in the nav to give context to the children.

My question is; how can I get the first child's URL within the ifchildren tags so I can make the parent automatically redirect to the first child's page in the navigation?

I know how to do this in regular forloops, but it would be nice to do this within Craft's nav tags.

Thanks,
Jay


texts:
I have image transforms set up and working well for my site, however I have an issue that seems to be a possible feature request because it is not documented or on this Stack Exchange.

If a user uploads an image that is smaller than the image transform setting, it scales the image up for them to the specified size. However this results in a pixellated image because of the upscale. What I would like to be able to do is only scale down images to the respective transform values, but if smaller, then keep their size, thus avoiding the pixellation and extra unnecessary file size.

Any tips?
Thanks in advance.


texts: Trying to launch Craft CMS site on 1&1.co.uk and told I don't have permission. Any help why?

texts: Does anyone know how to launch a Craft CMS site on 1&1.co.uk web hosting. I've uploaded my database, changed the siteUrl and uploaded the site with FTP but it's not working. I receive an error message (see image).


texts: Filter and sort Commerce products based on Matrix blocks

texts:
We have a website that uses Craft CMS v3.1.28 and Commerce v2.1.6.1. The below logic is implemented within a plugin and we're prepared to do custom implementations aka. prepared to go deep!

I would like to extend an existing ProductQuery with two innerJoins on a Matrix field. The matrix blocks represent product groups (by title; "contain") and sets the order of the product groups. I am currently getting duplicate rows (see code in first answer). I think I might have to innerJoin on the subQuery (generated below)..?

Now, we're currently using the code below to get the products and it works. However, it's not very efficient, since we then have to loop through the matrix and match by title to get the right order.

// $base_product_titles is the array of titles from the matrix blocks
// this query is obviously done per category
// additionally we have some filters ($types and $variant_criteria)

$base_products_query = Product::find()
        ->relatedTo($category)
        ->title($base_product_titles)
        ->type($types)
        ->hasVariant($variant_criteria)
        ->orderBy('type')
        ->with([
            'usage',
            'casing',
            'series',
            'defaultVariant',
            'variants',
            'variants.tire_size',
            [
                'variants.images',
                [ 'withTransforms' => ['product_overview']]
            ]
        ]);

PS: We group the above result by title in the template using |group('title').

I would appreciate any guidance!

Kind regards,
Meinhard


texts: Paginate entries ordered by a custom date field

texts:
I'm trying to paginate a bunch of events based on their start date. The order part is working correctly, but each consecutive page just loads the exact same entries. My code:

{% set events = craft.entries().section('events').limit(2).order('startDate asc') %}
{% paginate events as pageInfo, pageEntries %}

{% for event in events %}
    // Event content
{% endfor %}

{% if pageInfo.prevUrl %}Previous Page{% endif %}
{% if pageInfo.nextUrl %}Next Page{% endif %}

What am I missing?


texts: Craft throwing an SQL error on Save when Matrix field has a lightswitch

texts:
Since updating to 2.2.2587, anytime I edit an entry by adding a block on certain Matrix fields, it throws the following error:

Internal Server Error

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'field_text_markdown' cannot be null

It seems to throw the error if any of the blocks in that field contain a lightswitch field. It doesn't matter if the block with the lightswitch is actually added to the entry or not. In this case, my Matrix contains two switches, which are off by default.

Throws the error whether the blocks with the switches are present or not… and doesn't seem to matter if I add the blocks with the switches and turn them on or off.

Cheers!


texts: Is there an event that is triggered when an entry expires?

texts: I would like to update an entry after it has expired via a plugin. Is there an event that I can use to do this when using Craft 2?


texts:
I have setup an asset pool for all files our customer wants to upload using {basePath} and {baseUrl} variables which are defined in the configuration file.

Uploading files works
Selecting files to assign them to content works
displaying the files on the front page works
thumbnail generation in the backend does not work - returning 404 for the resized url
custom transforms for thumbnails on the front page do not work - 0-byte images get created which are of course empty

Nothing gets logged in the errorlog - everything seems to work fine.

I'm kind of lost currently - Project working nicely local but not on our server.
Any help on how to debug and solve this problem? Looks like an inconsistency problem inside of craft as some methods are accessing the assets correctly while others don't.

Here some files:

general.php

<?php return [
    'allowAutoUpdates'     => false, // Using shared craft, disable update triggering for customer - TODO: Completely hide update stuff in backend.
    'omitScriptNameInUrls' => true,
    'environmentVariables' => [
        'baseUrl' => CRAFT_SITE_URL,
        'basePath' => CRAFT_SITE_PATH
    ]
];

index.php

<?php

define('CRAFT_CONFIG_PATH',       'assets/configs/');
define('CRAFT_PLUGINS_PATH',      'assets/plugins/');
define('CRAFT_TEMPLATES_PATH',    'assets/templates/');
define('CRAFT_TRANSLATIONS_PATH', 'assets/translations/');
define('CRAFT_STORAGE_PATH',      'cache/');

define('CRAFT_SITE_URL',  substr($_SERVER['SCRIPT_NAME'], 0, -9));
define('CRAFT_SITE_PATH', substr(__FILE__, 0, -9));

require '../_craft/app/index.php';

.htaccess

# Compression
SetOutputFilter DEFLATE

RewriteEngine On

# No duplicate rewriting.
#TODO Remove and use [END] when Apache 2.4 is available on production.
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]

# Sass and JavaScript compilation and minification - except for admin backend.
RewriteCond %{REQUEST_URI} !admin/ [NC]
RewriteRule \.css$ scss.php [L]
RewriteCond %{REQUEST_URI} !admin/ [NC]
RewriteRule \.js$ js.php [L]

# Make bootstrap fonts available.
RewriteRule ^assets/bootstrap/(.+)$ vendor/twbs/bootstrap-sass/assets/fonts/bootstrap/$1 [L]

# Let craft handle everything else.
RewriteRule ^assets/icons/ - [L]
RewriteRule ^assets/images/ - [L]
RewriteRule .* index.php [L]

Both Environments have Imagick and GD available.

Environment Development: Ubuntu, Apache 2.4, PHP 5.6, MySQL 5.6

Environment Production: Debian, Apache 2.2, PHP 5.5, MySQL 5.5


texts: Need clarification on the need for a Single section being created

texts:
I created a single called recList and the corresponding Entry Template is /rec/list.html

I created an entry and I can view the webpage as you would expect.

Question: If I disable the entry or even delete the recList entry it seems to have no effect on the corresponding entry template, meaning that everything still works fine.  So, can someone explain the necessity of defining the single template pages in the admin site and what we are missing when we delete single sections?

Thanks!

Chip


texts:
I have a category with 2 levels. And I want to be able to let the user do a search based on those. The problem is that it needs to be AND between all level 1 categories, and OR within child categories. So let's say I have a category structure like this:
- Elevator
- Air condition
- View
  - Ocean
  - Mountains
  - Garden

Now when a user selects elevator, ocean and mountains I want to return all entries that have elevator AND (ocean OR mountains)
I tried this: $entries->categories(['and', 695, ['or', 698, 697]]);, but that doesn't work, as it seems to just skip the ['or', 698, 697] part.
Edit for bounty: In addition to the reason given above, there is also a change in the requirement since we added multiple categories. So for one category group, the operator needs to be OR, and some groups should have AND.


texts:
Is it possible to loop through locales? For example:

{% locale in craft.locales %}
    {# get link for each locale available #}
    {{ locale.title }}
{% endfor %}


texts: Fetch matrix field attributes in controller

texts:
In my controller I fetched the Entry

$criteria = craft()->elements->getCriteria('Entry');
$criteria->section = 'offlineEvents';
$event = $criteria->first();

The Entry has a matrix field with handler called eventDetails

How can I access this matrix field values? I want to do it like I'd do it in template:

{% for items in entry.eventDetails %}
    {% if items.getType() == 'heading' %}
     ....

but I cant do

foreach ($event->eventDetails as $details) { ... }

it's giving me empty array.


texts: Filtering category objects in a template?

texts:
So I have a Commerce product template page that grabs products something like this (segment 3 is the category slug):

{% set category = craft.categories.slug(craft.request.getSegment(3)).first() %}

{% set product = craft.commerce.products({
    relatedTo: category,
    status: 'live',
}).first() %}

However, I need this page to 404 if the category slug isn't in a collection of categories that are chosen in a global field:

{% for category in myGlobal.liveCategories %}
    These categories, like this one {{ category.title }}, are the only categories that are allowed right now
{% endfor %}

So I want to filter

{% set category = craft.categories.slug(craft.request.getSegment(3)).first() %}

against my global category field:

myGlobal.liveCategories

so that only the category that gets passed to my product loop is a valid category in the global set. Here is what I'm trying to accomplish, but this code block doesn't work:

{% set category = craft.categories.slug(craft.request.getSegment(3)).first() %}

{% if category not in myGlobal.liveCategories %}
    {% redirect 404 %}
{% endif %}

I assume I have to do some twig filtering, or create arrays and combine, ...or something.


texts: Use a single template to display entries from different channels?

texts:
I'd like to use a single template to pull in entries from different channels based on url segment 2. But it seems I need to change the section attribute to match the url segment:

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

Given that the url segment and section handle are different, can this be done?

For example the url segment might be hotel-california and the section handle of the section I want entries from could be hotelCalifornia or hotelsInCalifornia.


texts: In Craft 3, how to clear stuck "Deleting Stale Template Caches"

texts:
I've got 12 pending tasks, and can't get rid of the first stuck one.

CP->Utilities->Clear Caches doesn't seem to help.
In the database, in craft_queue there were five rows, the first one seeming to be the stuck one. I deleted all of those

Still the first task is stuck, and by now there are 14 tasks waiting.
I see that craft_templatecachequeries has over 11,000 rows. Would those be helpful to delete?


texts: Modify an ElementCriteriaModel to compare against numeric field

texts:
Can anyone tell me why this is returning all entries instead of entries with a creditsUsed field > 0? creditsUsed is a number field that I created for this entry type.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->authorId = craft()->userSession->getUser()->id;
$criteria->section = 'news';
$criteria->creditsUsed > 0;
$criteria->status = null;
$entries = $criteria->total();


texts: If I try to preview a previous revision of an entry, I get "an unknown error occurred"

texts:
Craft 3.3.15

Previous version of the entry was saved 1 minute ago, so no changes in settings between the two entries.

Any ideas on how to debug this?

Update - here's the error, which looks very much like what @mtnorthrop is getting:

2019-11-20 10:41:44 [-][1][-][error][TypeError] TypeError: Argument 1 passed to craft\helpers\ElementHelper::isTempSlug() must be of the type string, null given, called in /Users/andrei/Desktop/dev/hl/mailbuilder/vendor/craftcms/cms/src/controllers/EntryRevisionsController.php on line 473 and defined in /Users/andrei/Desktop/dev/hl/mailbuilder/vendor/craftcms/cms/src/helpers/ElementHelper.php:47


texts: How do you set up Craft CMS to back up your site automatically?

texts: I am considering having my site moved from WordPress to Craft CMS (feel free, by all means, to weigh in on this consideration), and wondered how one goes about setting up automatic backups within Craft. Thanks!


texts: Element-API migration - entries by category

texts:
I am having trouble getting the related category passed thru to the entry api endpoint.

I cant use :

   $criteria = craft()->elements->getCriteria(ElementType::Category);
        $criteria->id = $catId;
        $category = $criteria->first();

What is the equivalent in craft 3 api v2?

'api/v1/ship/category/<catId:\d+>.json' => function($catId) {
//old api craft 2
        $criteria = craft()->elements->getCriteria(ElementType::Category);
        $criteria->id = $catId;
        $category = $criteria->first();

//api craft 3
        return [
            'elementType' => Entry::class,
            'elementsPerPage' => 30,
            'criteria' => [
                'criteria' => ['section' => 'ship'],
                'relatedTo' => ['targetElement' => $category],
            ],
            'transformer' => function(Entry $entry) {
                return [
                    'title' => $entry->title,
                    'id' => (int) $entry->id,
                    'slug' => $entry->slug,
                    'postDate' => $entry->postDate
                ];
            },
            'pretty' => true
        ];
    },


texts: How to get users with birthday today in plugin/module?

texts:
How does one retrieve users from Craft3 DB whose birthday is today?

Birthdate field type is Date/Time.

Have a working PHP/MySQL example, but unsure how to port this to Craft3 syntax.

$sql = 'SELECT
            id,
            birthDate
         FROM
            !
         WHERE
            status = ?';

$users = $db->getAll($sql, array( USERS_TABLE,
                                  'active',
                                  date('j'),
                                  date('n')
                                )
                    );

Craft plugin

$users = \craft\elements\User::find()
           ->group('siteUsers')
           ->status('active')
           ->all();


texts: Re-using includes when the object type changes (entry vs block) - what is the best method?

texts:
So I am trying to reuse some include files built for a matrix builder that are also in some instances used as stand alone fields (Video, Downloads etc). The way I have coded this is that the object/handle changes from using block.handlename to entry.handlename what would be the most efficient way to code this?

Currently this is what I have done, but not sure it feels ‘right’?

So taking the video as an example. I have an include file _includes/matrix/video.html
I am then calling this from a Matrix Block like so;

{% for block in entry.mainContent.level(1) %}
{% switch block.type %}
{% case block.type %}
{% include '_includes/matrix/' ~ block.type %}
{% endswitch %}
{% endfor %}

And also an entry template like so;

{% if entry.video|length %}

        {% include '_includes/matrix/video' with { object : entry } %}

{% endif %}

In my video include file _includes/matrix/video.html I now have this;

{% set object = object ?? block %}
{% set url = object.video %}

    {{ url|videoEmbed({ byline: 0, autoplay: 0, rel:0 }) }}

But this means i need to this each time I am calling an entry? {% include '_includes/matrix/video with { object : entry } %} Is this the best approach?

Any suggestions/recommendations?


texts: Craft 2: get default user group from user settings

texts:
In Craft 2, I know I can get general config settings.

How can I get the current Default User Group (set in Settings > User Settings) for use in my templates?


texts: Is MariaDB required with Craft CMS or can MySQL be used?

texts:
I am currently installing Craft CMS on a test server, The server runs other development services. Currently installed on the server is MySQL 14.4.
Is Mariadb are requirement or can I utilise MySQL?


texts: How do I create an advanced route with multiple slugs?

texts:
I'm trying to create a route for an RSS feed which allows for the following routes.

domain/feed
domain/category/feed
domain/category/subcategory/feed

I have the first two routes working and the category fetching logic looks okay to me.

So far in my routes file I have the following

'feed' => 'feed/_index.twig',
'(?P<slug>[^/]+)/feed' => 'feed/_index',

// Additional New route
'(?P<slug>[^/]+)/(?P<slug>[^/]+)/feed' => 'feed/_index',

That last line was added recently as I thought the child category would include the parent category in its route.

I either get a 404 error without that new route, or when I do add that third route I get the following error

preg_match(): Compilation failed: two named subpatterns have the same
name at offset 27 (craft/app/etc/web/UrlManager.php:387)

Any help would be greatly appreciated.


texts: Retrieve entry field value from a different locale?

texts:
Is it possible to retrieve a field value from an alternate locale? I'm working on a multi-language dictionary website and it would be helpful to display values for an entry in more than one locale (language), while the main content stays in the current locale. Right now I have something setup like this:

{% for word in dictionaryWords %}
    {# returns definition for the word in the current locale #}

{{word.definition}}

{% endfor %}

I'd like to add a secondary definition in another language from a different locale. Something like this, but I'm not sure how to get at the field data from a different locale.

{% for word in dictionaryWords %}

  {# returns definition for the word in the current locale #}

{{word.definition}}

  {# returns definition for the word in a secondary locale #}
  {% if currentLanguageID == "languageID1" %}

{{ word definition in language 2 }}

  {% elseif currentLanguageID == "languageID2" %}

{{ word definition in language 1 }}

  {% endif %}

{% endfor %}


texts: Freeform - How to use fieldSearch with table field?

texts:
I have a table field with handle "attendee".

I would like to search for submissions using data in this field.

None of the below works:

$result = Submission::find()->fieldSearch(['attendee'=>'xyz@abc.com'])->all();
$result = Submission::find()->fieldSearch(['attendee[]'=>'xyz@abc.com'])->all();

Please help, thanks.


texts:
I have a website with a few thousand entries. At the bottom of the entry template, we show 4 random news posts from the last 4 weeks.

Now, when someone adds a new entry, the DeleteStaleTemplateCaches task starts running. This causes cpu and memory peaks on our server that go to 100%. This task also takes about 30 minutes to complete, meaning that our cached homepage only shows the new article after 30 minutes.

Any ideas why it takes so long, solutions on how to fix this? (Apart from caching the 4 entries on the bottom of the page, and caching the homepage, we didn't do anything weird.)


texts: How to filter entries in multiple category groups by selecting multiple categories

texts:
This question is very similar to the question posted here I have asked in the comments but my requirements are slightly different. I am trying to filter search results by categories in more than one category group and use both an exclusive search (category AND category) and a non exclusive search (category OR category).

My use case is this: the parks category wants to filter using the OR filter so Park A OR Park B and so does the price filter so Price A OR Price B but when they are combined Park A AND Price B only show parks in the Price A category.


texts: Do I need to change the date.timezone in php.ini?

texts: If I set my timezone in server and in Craft general settings, do I still need to change it in php.ini? And how does Craft handle timezone in those three places?


texts: Changing the "homepage" url for logged-in users

texts: I know I can set  postLoginRedirect in config/general.php to send the user to a specific page after login. Is there a way to grab that value in the template? This came up because I noticed that the {{siteUrl}} href in the default _layout.html template was sending the user to the homepage (index.html), but I'd like to conditionally replace that link for a logged-in user.


texts: How to create a plugin which will update a field in a section when an entry is saved

texts:
I am looking to create a plugin which will update a field in a section when I save an entry.

I will be getting the length of an MP3 file (using FFMPEG) I upload via assets and output the time to another input.

I can listen out for the onSaveEntry event, but I am unfamiliar with getting and putting data in a craft plugin.

Any help would be appreciated.


texts: Craft Commerce: Validation on Address Fields

texts:
Can someone break down how I should validate empty address fields as a plugin for Craft Commerce and take the following answer further?

The Craft Commerce documentation provides the following example for the name field - but I'm not sure what my next steps should be...

public function init()
{
    craft()->on('commerce_addresses.onBeforeSaveAddress', function($event){
            $address = $event->params['address'];
            $address->addError('firstName','Not a cool name man.');
            $event->performAction = false;
    });
}


texts:
I'm trying to get rid mix content warnings for https connection. The SSL certificate is installed and working fine but my image transforms are being requested over http hence the warning messages.

Looking into the docs I have tried:

url={{image.getUrl(thumb, null, 'https')}}

But that didn't seem to make a difference. Has anyone encountered this issue before?


texts: How can I get spaces to render in my dropdown option label template call?

texts:
Example

Let entry.dropdownOption.label = "option with spaces"

{% for entry in entry.dropdown %}
    {{ entry.dropdownOption.label }}
{% endfor %}

renders as in my template: "optionwithspaces"

How can I instead get it to render as "option with spaces"?


texts:
I've installed Craft 3 through composer and I'm attempting to work through the setup process within terminal:

MacBook-Pro:~ jamie$ ~/Documents/repos/__craft-3-beta/craft setup
Which database driver are you using? [mysql,pgsql,?]: mysql
Database server name or IP address: [localhost]
Database port: [3306]
Database username: [root]
Database password:
Database name: craft-three
Database table prefix:
Testing database credentials... failed: SQLSTATE[HY000] [2002] No such file or directory
Which database driver are you using? [mysql,pgsql,?]: mysql
Database server name or IP address: [localhost] 127.0.0.1
Database port: [3306]
Database username: [root]
Database password:
Database name: [craft-three]
Database table prefix:
Testing database credentials... failed: SQLSTATE[HY000] [2002] Connection refused

Notice that I get 2 different errors when using the IP add and localhost for DB_SERVER

I also cant get it working when manually filling in the .env file.

I'm using MAMP Pro on a Mac.

Any help on this will be greatly appreciated.


texts: Database structure for Craft 3 to import from external source?

texts: Is there any best practice how to import info Craft 3 data from external source, or should I backtrack it from the database?


texts:
struggling to decipher how to link a plugins controller to an action route. The docs say to use "https://pluginfactory.io/" to scaffold one, but what it generates is a different structure to what the documentation say to use.

I've got a plugin called Gated Content sitting inside: plugins/gated-content

I've got a controller named and located at:

plugins/gated-content/src/controllers/GatedContent_DataCaptureController.php

with the class name of of GatedContent_DataCaptureController

I've just got an actionIndex method which var dumps and exits.

Which would suggest (according to the docs) that the URL to access this should be:

https://craftcms.localhost/index.php?p=actions/gatedContent/dataCapture/index

But it just throws a 404.

Inside of the .craftplugin file I've also added "controllerName":"GatedContent_DataCaptureController incase, but doesn't seem to make a difference.

What is the correct pattern to use for each of these?

Thanks


texts: 8-bit png's get distorted when you upload them

texts: When I upload an 8-bit transparent png, it gets distorted. Is there any way to fix that?


texts:
Every couple of weeks or so, all the sites on my server (all running Craft) go down with the error message:

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1286 Unknown storage engine 'InnoDB'

It seems unique to Craft and unique to this server. None of the sites are particularly busy. It's likely a server thing, I know, but has anyone run into this and got a fix?

Thanks,
Clive


texts: Downloading file from custom element action

texts:
I'm trying to download a CSV file from a custom created element action

Here's the performAction function

    public function performAction(ElementCriteriaModel $criteria) {
        $contents = 'row1column1,row2column2'.PHP_EOL.'row2column1,row2column2'.PHP_EOL;

        craft()->request->sendFile('export.csv', $contents, array('forceDownload' => true), false);

        return true;
    }

No error is thrown, the code passes right through the function. When I check the craft logs, there's no sign of any error

And yet, there's no download occuring. When I try this same code in a controller or a service, it works just fine. But in this element action class, nothing happens


texts: Send freeform email notification to manually entered recipient address

texts:
I'm trying to build a "send this page to a friend" form in Freeform. My code looks like this:

{% set form = craft.freeform.form("emailToAFriend") %}

{{ form.renderTag({returnUrl: "contact/success"}) }}

    {% if form.hasErrors %}

            {{ "There was an error submitting this form"|t }}

    {% endif %}

    {% set recipientsName = form.get("recipientsName") %}
    {% set recipientsEmail = form.get("recipientsEmail") %}
    {% set yourName = form.get("yourName") %}
    {% set yourEmail = form.get("yourEmail") %}
    {% set sharedUrl = form.get("sharedUrl") %}
    {% set message = form.get("message") %}

    {{ yourName.label }}
    <input name="{{ yourName.handle }}" value="{{ yourName.value }}" />
    {{ yourName.renderErrors() }}

    Your Email Address
    <input name="yourEmail" />
    {{ form.get("yourEmail").renderErrors() }}

    {{ recipientsName.label }}
    <input name="{{ recipientsName.handle }}" value="{{ recipientsName.value }}" />
    {{ recipientsName.renderErrors() }}

    Their Email Address
    <input name="recipientsEmail" />
    {{ form.get("recipientsEmail").renderErrors() }}

    {{ message.renderLabel() }}
    {{ message.renderInput() }}
    {{ message.renderErrors() }}

    <button type="submit">Submit</button>

{{ form.renderClosingTag }}

How could I get the field in recipientsEmail to pass to that recipient and choose the template?


texts:
Just wanted to know if there's an easy way to hook Solspace Freeform submission to external API?

I got a form built using Solspace freefrom Pro, and I'd like to post each submission of the form to an external API. Whats the easiest way to go about this using Craft?


texts:
I am getting some global entries from the CMS that I want to use as meta-tags content.

When I load the page I see in the inspection that the meta-tags are moved inside the body.  When I remove the dynamic meta-tags and use only the hardcoded, everything is ok.

I have something like that in the head:

{% set metadata = craft.globals.getSetByHandle('metadata') %}

<title>{{ metadata.title }}</title>
<meta name="description" content="{{ metadata.description }}">
<meta name="keywords" content="{{ metadata.keywords}}">

Why the meta-tags are moved? How can I fix that? Is it a Craft issue or a Twig issue or my mistake?


texts: Migrate WordPress Site into Craft CMS. How deal with 404's?

texts:
I migrate my WordPress site into Craft CMS. So far so good.
But the URLs for most of the Blog Entries are complete new. What's the best way to handle that? My site is good linked on Google and there are a lot of backlinks. It would be nice to have a solution where I can see which pages the Users call and if it a 404. Afterwards I can create rewrite rules for this sites.

Finest way was a Plugin that combine this two features.
Maybe anyone knows one.


texts: Next / Prev and looping/cycling entries instead of reaching the end of the selected results

texts:
Is there a way to be able to use entry.getNext(params) to return back to the first entry when you're viewing the last entry in the parameters?

With the result of looping/cycling through all entries and returning to the original.


texts: Possible to get the Freeform plugin to send to different admins based on locale

texts:
I'm using the Solspace Freeform plugin.

If someone submits a form on /de/contact I want it to go to a German admin

If someone submits a form on /en/contact I would like it to go to an English admin.

In Expression Engine, you used to be able to set recipients in the template.

Is the best way to deal with this to setup a "Dynamic Recipient" field, then hide it in the markup and somehow deal with this on a locale conditional?