texts:
I've started off with this solution:
http://craftcookbook.net/recipes/330

{% set testsByAllergenGroup = {} %}
{% set entries = craft.entries.section('tests').order('title asc') %}
{% set groups  = craft.categories.group('allergenGroup') %}

{% for group in groups %}
  {% set entries = entries.relatedTo(group) %}
  {% if entries|length %}
    {% set testsByAllergenGroup = testsByAllergenGroup|merge({
      (group.title): entries
    }) %}
  {% endif %}
{% endfor %}

    {% if groups|length %}

Allergy Groups:

            {% for group in groups %}

{{ group.title }}

            {% endfor %}

      {% for groupTitle, groupTests in testsByAllergenGroup %}

          {{ groupTitle }}

          {% for entry in groupTests %}

{{ entry.title }}

View Details

Add to Cart ($40)

          {% endfor %}

          BACK TO TOP

      {% endfor %}

    {% endif %}

I'm hoping to output the group title and slug, but this code will only allow for one variable to be set in the merge set:

{% set testsByAllergenGroup = testsByAllergenGroup|merge({
  (group.title): entries
 }) %}

I'm hoping to do something like this:

{% for group, groupTests in testsByAllergenGroup %}

    {{ group.id }}

Can you guys help me out? Thanks!

p.s. this is my first major Craft CMS project so Twig is new to me ;)


texts:
I see from the Craft's default remove index.php htaccess code here that the following line takes into account favicon.ico files.

RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]

I was wondering, with the many different file names of favicons these days would it be ok to make the rule look like this:

RewriteCond %{REQUEST_URI} !^/(.*\.ico|.*\.png)$ [NC]


texts:
Our client has created a lot of folders and sub-folders to keep their assets organised. I would guess they've made around 700 to 800!! (Basically two folders for each post)

The assets page in the CP loads very slow now - is there anything I can do to speed this up?


texts:
I'm having problems setting up an event. It gets triggered and I can access the event's params array, but I can't override the value like I can with Craft's default events.

MyPlugin_myServiceService.php

public function setTest()
{
    $test = true;

    $event = new Event($this, array(
        'test' => $test
    ));

    $this->onAfterSetTest($event);

    return $test;
}

public function onAfterSetTest(Event $event)
{
    $this->raiseEvent('onAfterSetTest', $event);
}

MyOtherPluginPlugin.php

craft()->on('myPlugin_myService.afterSetTest', function(Event $event)
{
    $event->params['test'] = false;
});

Not sure what I'm doing wrong but
craft()->myPlugin_myService->setTest() returns true.


texts: How does the Structure section type work?

texts:
I read the documentation but I'm still confused about the Structure sections..

What they are usually used for? What are the advantages of using it?
And most important how to use them?

Please can you explain with some examples?


texts: Assigning the right license to the right subdomain

texts:
My client has 3 licenses, one for each of 3 subdomains. Let's call them A, B and C.
C has been derived from B, so has inherited B's license.key. How should I assign the correct license to C? Or does it not matter as long as the appropriate number of licenses have been purchased?
On a related note, my client's id.craftcms.com log stores the same root domain against all of them, so I have to put a reference to the subdomain in Notes. Not a problem as such, but the same domain for all seems  a bit imprecise.


texts: I have some entries that I'd like to move to a different channel, but I don't see any way to do this. Is it possible?


texts: Sort matrix blocks by date and limit to 10 entries

texts:
I'm loading multiple matrix blocks from multiple entries to the homepage if the date is today or in the future. So far this works but now I'm trying to sort the blocks by date and limit the output to 10 dates.

Here's the code I'm currently using:

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

  {% for block in entry.agendav2 %}

    {% if block.Datum >= now %}

      {% switch block.type %}

        {% case 'Datum' %}

              {{ block.Datum|date("d.m.Y") }}
                {{ block.locatie }}

              {{ entry.globalTitle }}
              {{ block.evenement }}

      {% endswitch %}

    {% endif %}

  {% endfor %}

{% endfor %}

Right now it's loading every upcoming date per entry like:

Entry 1: 31-01-2018
Entry 1: 01-02-2018
Entry 1: 02-03-2018
Entry 2: 30-01-2018
Entry 2: 06-02-2018
Entry 2: 03-03-2018
Entry 3: 23-01-2018
Entry 3: 25-01-2018
Entry 3: 08-03-2018


texts: How would I pull in the first Matrix block including certain blocks only

texts:
I have a Matrix field setup. I want to be able to pull in the first Matrix block used to print a snippet, but only out of the blocks 'text' or 'textImage'. So the first one used, out of those two only.

This is what I have but it's pulling in the textContent block regardless, even if the text block is first.

    {% set textBlock = entry.body.type('text').first() %}
    {% set textBlock2 = entry.body.type('textImage').first() %}

    {% if textBlock %}

{{ textBlock.textContent|hacksaw(chars='100', append='...') }}

        {% else %}

        {% if textBlock2 %}

{{ textBlock2.text|hacksaw(chars='100', append='...') }}

        {% endif %}

    {% endif %}


texts: With Element API, can I combine two entry types into a JSON object, keyed by type?

texts:
I need to return two types of entry to an external service, and am trying to do so in one endpoint.

I am able to return all of the instances of each type, but it returns an array of mixed types.

"api/myEndpoint" => function() {
        return [
            "criteria" => [
                "type" => ["typeOne", "typeTwo"],
            ],
            "transformer" => new MyTransformer()
        ];
    }

I'm trying to achieve: { "data": { "typeOne": [{...}, {...}], "typeTwo": [{...}, {...}]}}

I can think of various workarounds for this specific case. It would be easy enough to add a type field within the Transformer, and sort them on the other side. Or, simply make two calls. However, our team was planning on using Craft as a headless CMS for future projects, and it's important to me  be able to control the structure of Element API's JSON response.


texts: How to append current version to post URL - versioning a post

texts:
I'm middle of a PWA app and one of the problems facing is versioning, once the post cached using Service Worker and if any change amended(ex: if it is an event post, the event end date may be extended.) to the post still user sees the old post.

https://sample.com/event/this-will-happen-after-covid?v=12042020

If I can add 'Date Updated' as a parameter of the URL I hope I can manage with. If there better approach, much appreciated.

The second question about csrf token please check the example.

        let api = '/actions/favourite/get-favourite-ids';

        let data = {
            'id': {{ currentUser.id }}
        };

        data['{{ craft.app.config.general.csrfTokenName }}'] = '{{ craft.app.request.csrfToken }}';

        $.ajax({
            url: api,
            type: 'POST',
            data: data,
            dataType: 'json',
            async: false,
            success: function (result) {

                addFavoriteIcon(result)

            },
            error: function(jqXHR, textStatus, errorThrown) {

            },beforeSend: function(){

            },
            complete: function(){

            }
        });

I realised that due to csrf token is also cached, 400 error produced.

What are the better approach get rid of these two issues?


texts: Merge element type errors? (title + hard-coded field)

texts:
My plugin has a custom element type. The element type uses a standard "title" field, implemented by MyElementType::hasTitles() returning true.

In addition, my element type contains a few hard-coded fields. The whole plugin has been built out and working great, I'm very happy with how all of the components interact.

However, I'm trying to refine the validation of when an element is saved. It's easy to make a field required by simply adding 'required' => true when defining the field in my Record. And when a user attempts to save an element without filling in that field, the proper error message will be triggered and displayed in my template.

But here's the catch...

If the user leaves empty both the title field and my hard-coded field, only one of them will display an error message at a time. Specifically, only the hard-coded field will display the error message first. Once that has been filled in, the title error message will be triggered on the second submission.

What am I missing? Is there a specific way to merge these error messages together so that they are both returned to the template at the same time?


texts:
Hi I've created a plugin that has an action in the controller that looks at a user registration form when submitted and if the username is empty creates a unique username for the user. This works fine and saves the user with the random name or with their chosen name if a username is entered. My problem is I am not getting any errors returned to the form or a success message when the user is registered. Validation appears to be happening as the user is not being registered if errors are found. Although the only error I see printed is invalid email if entered incorrectly, if the password is missing there is no error returned but the user is not registered.

My code to add the model is as follows. Can anyone point me in the right direction so that the errors are returned. The template is the standard registration form from the craft documentation.

$newUser = new UserModel();
$newUser->username = $username;
$newUser->email = $email;
$newUser->newPassword = $password;

if ($newUser->validate())
{
    craft()->users->saveUser($newUser);
}
else
{
    return $newUser->getErrors();
}


texts: Find entries that use a specific block in their Matrix field?

texts:
Suppose a Mtrix field named MyMatrixField has three blocks called Text, Images, and Buttons.

What MySQL query would list the section and title for all entries whose MyMatrixField field has a Buttons block in-use?

Something like:

SELECT section, title FROM `craft_entries` WHERE `field_MyMatrixField_Buttons` IS NOT NULL


texts:
I am getting the following Twig error and I cannot figure out what is wrong. I'm new to Twig.

Twig Syntax Error – Twig\Error\SyntaxError

Unexpected "minify" tag (expecting closing tag for the "cache" tag defined near line 5).

in /var/www/craft/templates/index.twig at line 5

{% extends "_layouts/_layout.twig" %}

{% import "_partials/_macros.twig" as macros %}

{% block content %}

{% cache using key "home-page" %}{%- minify -%}

{% set banner = entry.homeBanner.one() %}

{{banner.heading}}

      {% set bannerBtn = banner.button.one() %}
``


texts: How do I store and retrieve elements for ElementSelectField? Getting error "Call to a member function getUiLabel() on array"

texts:
I have a field that allows a user to select multiple products and save them to the database for a plugin, but when I try to retrieve these values and have them selected in my form I get the error

  Call to a member function getUiLabel() on array

Here is my field

{{ forms.elementSelectField({
    label: "Products Allowed",
    instructions: "Leave blank if this voucher has no product limits",
    id: 'products',
    name: 'products',
    elementType: productElementType,
    selectionLabel: "Add Products"),
    elements: (products is defined and products ? [products])
}) }}

The first question is, how do I store these values? Do I store it as it comes back? In an array, or do I encode that array to JSON? I've done both and both ways give the same error at retrieval.

Here is my retrieval code

$products = JSON::decode($variables['voucher']->products);

$variables['products'] = [];
foreach($products as $productId)
{
    $product = Commerce::getInstance()->getProducts()->getProductById($productId);
    ArrayHelper::append($variables['products'], $product);
}

As mentioned before, I've also just tried saving the products array without encoding to JSON and applying the saved results directing to $variables['products'] with the same results.


texts:
It mentions developers can use it for personal usage. Does that include commercial usage as well? It seems so, but am not sure.

I have a few small personal sideprojects running with some Adsense and Affiliate links (currently on CodeIgniter, etc.).


texts: CSRF token creation and Content-Security-Policy header

texts:
I've just updated my site with setting my Content-Security-Policy Header and after fixing the slew of errors which popped up in the console, I am now down to one.

The relevant part of my .htaccess file is script-src 'self'. Here I do not set 'unsafe-inline' as that kind of goes against the point of setting the CSP in the first place - at least in my reading.

With Craft setting a CSRF token and my site doing POST requests over AJAX, I set the token name and value as recommended here: https://craftcms.com/support/csrf-protection - which is inline and above in my CSP I do not allow inline scripts. So as you can see it falls apart and Craft spits out a 400 error.

Is there any way I can get around this? I'd like to keep my CSP and with CSRF being enabled by default in Craft 3, I'd like this ironed out before then.


texts:
I have a lot of data that sits outside of Craft (the data is in MS SQL Server) and I plan on writing a simple .NET Service which will return JSON. I need to display this data but not sure on how to connect to a service using Craft CMS.

Are there any clients (plugins) which will connect to a service get the JSON data and display it?


texts:
Had absolutely no issue with an older version of their host on the installation and running a Craft CMS site.

This one has been a bear

Is there a step by step on best way to install

The only real difference I see is MariaDB, yet they assured me it was just a top layer of MySQL

cPanel Version  66.0 (build 23)
Apache Version  2.4.27
PHP Version 5.6.31
MySQL Version   10.2.9-MariaDB
Architecture    x86_64
Operating System    linux

Thanks


texts:
I want to display different code blocks if a category level is 1 or 2 or 3 – on a category page, but finding this hard to do,
if I'm on an entry page I can use:

{% if entry.level == 1 %}

how can I use the equivalent but for a category on a category page?
Thanks


texts:
I haven't used categories before so maybe I'm looking at this the wrong way.

I currently have a category group named products with the following structure:

Featured
Fruit
----Apple
----Banana
Veg
----Turnip

I know I can do the following to show just the subcategories of fruit:

for cat in craft.categories.group('productCategories').descendantOf("fruit ID")

But how do I get the "fruit ID" when I'm on the on the fruit page?

 craft.categories.relatedTo(entry)

returns all the categories in products but I want just the current category.

Any help greatly appreciated!


texts: Impossible to access an attribute ("url") on a null variable in search results

texts:
I have a search results page set up like this:

{% set searchResults = craft.entries(queryParams) %}
{% paginate searchResults as pageInfo, pageEntries %}

{% if pageEntries|length %}
  {% for yacht in pageEntries %}
    {% set prevEntry = item.prev %}
    {% set nextEntry = item.next %}
    Link
  {% endfor %}
{% endif %}

That works fine except that it outputs the entry title of the next and previous entries. If I do nextEntry.url or prevEntry.url (or slug) I get:

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

Why is that?


texts: Uploading assets to different locations based on environment

texts:
I'm currently working on a new Craft CMS website for my company. We're using Elastic Beanstalk for hosting, which means that saving assets to file on the server isn't really viable- they get overwritten by code deployments- so I'm planning to have them saved to S3.

However when I or other developers are working on the site locally, uploading to S3 is both unnecessary and difficult (the company handles a lot of sensitive data so individual access to any of our AWS services is heavily ring-fenced). It would be preferable in development to just upload images to file locally and keep them out of version control.

Ideally I'd like to be able to change the root asset location depending on the environment. I've done similar things in Rails and Express apps, but am very new to Craft and PHP in general and am not sure where to begin. The official AWS integration seems to assume that you want everything going into S3 all the time. Does anyone have any experience of using different upload locations for different environments?


texts: How do I get the Settings System email Address?

texts:
From a template or a plugin, how can I get the value of admin/Settings/System Email Address ?
Thanks for your help
Nicolas


texts: List entries of documents in a section grouped by checkbox

texts:
I'm trying to list entries in a section which are documents. Those documents are grouped by checkbox. I'd like to list the document title and the asset in the entry's url. I only want to list assets which have a specific checkbox ticket.

I was able to output and group the assets by checkbox, but I'm struggling to find that entries asset url. Any thoughts?

This is what I have so far:

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

{# get all checkbox options #}
{% set options = entries.first().documentType.options %}
{% set assets = entry.documents %}

 {% for entry in entries if entry.documentType.contains('Report') %}
    {% for asset in assets %}
       {{ entry.title }}
    {% endfor %}
 {% endfor %}

Unfortunately as expected the {{ asset.url }} returns the url of the entry and not of the asset documents which is attached to the entry.


texts: Craft Commerce starting order ids form a higher number?

texts:
Is there a easy way to start Craft Commerce order ids form a higher number?
So the can follow on from an old system and not overlap?

autoincrement in the DB table maybe?


texts: Sort entries by time part only of DateTime object

texts:
I am trying to

filter and sort show entries by what time they begin
display the current show

I have two fields, startTimeand endTime, and while Craft lets me display only the time part in the Control Panel, I can't filter entries in my template by the time part only.

Listing out entries:

{% set shows = craft.entries({
    section: 'shows',
    order: 'startTime asc',
    day: 'sunday',
}) %}

Displaying the current show:

{% set nowPlaying = craft.entries({
    section: 'shows',
    startTime: '<= ' ~ rightNow | date('c'),
    endTime: '>' ~ rightNow | date('c'),
    day: rightNow | date('l'),
}) %}

If I create all my show entries on the same day, filtering by the whole date is fine, but that's assuming

the times are never changed (thus updating the date)
I don't care to know what show is currently playing (because a show will only show up if I created it today).

I prefer not to reinvent the wheel by making a template-side sorting algorithm. Is there not a more elegant way to query just the time part in Craft filtering?


texts: Twig Templates : Include dynamic data when using set

texts:
I'm trying to use the Encode Email plugin to encode email addresses.

The email addresses are dynamic so I need to include the output from the database when I'm using set.

This is their example that doesn't use dynamic info:

{% set email = "Your Name" %}
{{ email | rot13 }}

And this is what I've tried that doesn't work.

{% set email = "{{ contactInfo.contactEmail }}" %}
{{ email | rot13 }}

Is there a way to include the dynamic variables into the set statement?


texts:
I’ve installed CraftQL and can successfully query from the Craft admin interface but when I hit the endpoint using Axios I get a 500 server error. I've checked that my endpoint matches what's set in CraftQL's settings. Any idea why this is failing?

Here’s my Axios code:

axios
  .create({
    baseURL: "/api",
    headers: {
      Authorization: `Bearer R0Fq9-AAAAA-7hXQrigZqiFfq9BevLGdHrZWn6FNVaABCJsq-CZQuGxqklmntl`,
      "X-Requested-With": "XMLHttpRequest"
    }
  })
  .post("", {
    query: `
    {
    entries(section:[testSection], limit:5) {
      ...on TestSection {
        title
        url
      }
    }
    }
`,
    variables: ""
  })
  .then(result => {
    console.log(result.data);
  })
  .catch(error => {
    console.log(error);
  });


texts: Include single entry type with custom parameters in the for loop within multiple entry types

texts:
I have several entry types, where I want to set a special element criteria for the entryTypeHandleX entry type, and simultaneously loop through all entry types included entryTypeHandleX.

The criteria I want to set is to skip first X entries for entryTypeHandleX.

In my template it looks like this:

{# Set ECM for all sections and entry types #}
{% set params = craft.entries.section().types() %}

{# Set ECM for all channels and special entry type #}
{% set special = craft.entries.section().type('entryTypeHandleX').offset(X) %}

{# Set ECM for entries. Check var 'params', Where the data are coming from!!! #}
{% set entries = params.limit(10) %}

{% paginate entries as entriesOnPage %}

{% for entry in entriesOnPage %}
{# entry #}
{% endfor %}

{% endpaginate %}


texts: Freeform | Create Asset Subfolder Based on entry.id with File Upload Field

texts:
I am using Freeform 3 to update existing entries with a file upload field. Everything works but I would like the path to the asset to include the current entry.id I am editing.
fileUploadPath/123
The docs hint that I can do something like this but I can't get it to work with the entry.id.
Upload Location Subfolder (optional) - the subfolder path that files should be uploaded to. May contain form.handle or form.id variables or something like currentUser.id for folders based on user ID's or "now"|date("Y/m") to dynamically generate folders based on dates as well.
currentUser.id works, form.handle and form.id work; but when I try entering any combination of entry.id, {{ entry.id }} { entry.id } it submits the file without error and folders are created but they are called "/entry.id" etc without using the actual entry.id number as desired.


texts: Plugin: Linking elementSelectField to own plugin models

texts:
I'd like to have an elementSelectField in my plugin. The goal is to select a Company which is defined by my plugin Model. So when clicked, it'll display a list of companies in the Dialog box and you select or search for them, then close it (Same way as selecting Assets).

Is there an example I can see out there or perhaps some guidance? Do I need my own FieldType?

Cheers,
Ryan


texts: Craft Commerce 3 Decrease line Item qty by one?

texts:
I may be missing something obvious but I'm trying to update a +/- quantity button system for adding products to work on Craft Commerce 3
The desired functionality is that click '+' increases the cart amount for that item by one, clicking '-' decreases the cart amount for that item by one.
The original build was in commerce 1, and the apparent way it was written was just by running an update cart ajax call (at what was then 'commerce/cart/updateCart') and passing through a '1' or '-1' as the quantity value. That doesn't appear to work anymore. The '+' call will add the '1', but passing the '-1' through for the '-' call does nothing. It just returns the same cart as if I passed through a zero.
I tried with 'commerce/cart/remove-line-item' but that removes all quantities of the line item rather than just decrement it by one.
I've tried passing the following into an ajax post request:
var data = {
            ['CRAFT_CSRF_TOKEN']: token,
            action: 'commerce/cart/update-cart',
            lineItems: {[lnid]: {'qty': dec}}
        };

With lnid being the line item id and dec being the new desired quantity (I also tried -1 there) but that just destroys the line item completely.


texts: Craft 2.3 new User does not set the default permissions group

texts:
Hello I do not know if this is a bug or something but we just updated to craft 2.3 and got an issue which we did not have previously.
In user settings we can set the default permissions group but when we do create a new user this group is not applied to that user.Im not sure why this is, maybe something more needs to be done beginning Craft 2.3 but the simple flow of creating a new user worked previously. Upon the user account creation the default group would be set automatically.

EDIT:

Thank you for your answers. I was mistaken it is assigning the group but I cant get that group on an event trigger.

    craft()->on('users.saveUser', function(Event $event) {
        $user = $event->params['user'];
        var_dump($user->getGroups()); exit();
    });

I am doing the above in my plugins main PHP file and for some reason before updating it would give me the users group as the default one already assigned. After the update I get a empty array even though going to the control panel after registering I can see that the new user has the group assigned.


texts:
If I create an entry with international characters in urls? e.g. for Polish language?

If I create an entry with the word "ułatwienia" in the url, it doesn't work (I get Craft serving up the 404 page), I take out the special ł character and it's fine.

Although interestingly, the Live Preview url works fine with the special character included.

Have I missed something?


texts: Image Transform Problems, Timeouts, Stuck Transforms

texts:
We are seeing the following symptoms:

We routinely encounter stuck Generating pending image transforms tasks and have to manually mark the tasks as failed using SQL in the table craft_tasks.
Broken image links on pages that use image transforms. This can sometimes be fixed with multiple page refreshes.
The phperrors.log message PHP Fatal error:  Maximum execution time of 120 seconds exceeded in /.../craft/app/vendor/imagine/imagine/lib/Imagine/Imagick/Image.php on line 228, even though are php.ini sets the max execution time to 300. I am pretty sure this is from the hard-coded limit set in AssetTransformsService.php

Our site has a large variety of images; the site is for a advertising agency. We can reproduce the problem pretty easily with animated GIFs, although size of the GIF does not alone seem to be the factor, because some 2mb GIFs never transform, while some 4mb GIFs transform very quickly.

I think there are a few issues going on:

The 120 second limit is affecting some images that take a long time to transform, resulting in a exceeded exec time log message.
Some images are never completing the transform process, seemingly regardless of the transform time, resulting in an exceeded exec time log message.
Some images mysteriously get stuck in the image transform process, resulting in no log messages.

Questions

What is the recommended way for increasing the hard-coded 120 second limit?
How can we track down the cause(s) of the stuck transforms?

AssetTransformsService.php Background

The Craft core file craft/app/services/AssetTransformsService.php has a hard-coded PHP max_execution_time of 120 seconds.

line 421: ini_set('max_execution_time', 120);

Some Craft Info

We are using Craft CMS version 2.6

Some Sever Info

We have imagick enabled as our image driver.

imagick module version  3.4.1
Imagick compiled with ImageMagick version   ImageMagick 6.7.2-7 2016-06-16 Q16 http://www.imagemagick.org
Imagick using ImageMagick library version   ImageMagick 6.7.2-7 2016-06-16 Q16 http://www.imagemagick.org
ImageMagick release date    2016-06-16


texts:
The elementApi docs state you can use custom elementTypes via plugins.  I am using craft commerce which states it creates the custom elementType 'purchasable'

I've tried:

return [
'endpoints' => [
    'category.json' => [
        'elementType' => 'purchasable',
        'criteria' => [
            // 'category' => 'products', // randomly trying stuff here!
            // 'section' => 'products',
            // 'type' => 'products',
        ],
        'transformer' => function(EntryModel $entry) {
            return [
                'title' => $entry->title,
                'url' => $entry->url,
            ];
        },
    ]
]]

I've tried many variations on the word purchasable, as we as random guesses like 'product', 'item' etc etc

I should mention I am able to JSON back with all categories, Entries etc etc

I am sure this is possible, as craft, craftcommerce and elementApi are all made by the same guys!

Any help would be amazing


texts:
Has anyone set up the Charge plugin with Stripe Connect? I've followed the docs and things look good in the Craft back-end but the payments don't look to be routed to the correct Stripe accounts on the Stripe end.

The Squarebit docs refer to a config setting which I need but I haven't been able to track this down.

https://squarebit.co.uk/software/craft/charge/usage/controllers/connect-controller


texts: Plugins get removed after publishing to Heroku

texts: I'm using Heroku and every time I push changes to Heroku, the plugins installed from the plugin store get removed. Do I need to add them to my composer file manually?


texts: How to pull an entry's SEOmatic meta tags with Element API?

texts:
How do I get the meta tags used in SEOmatic for a specific entry and returning it through the Element API?

Not sure how the PHP code looks like when using SEOmatic's PHP API.


texts: What's the difference between total function and count function?

texts:
I found out that the functions count and total on the elementCriteriaModel show different results:

The following examples gave different results. paginate.total was the same as total, but not correct. Only count showed me the correct answer.

{% paginate craft.entries(filterParams).section('object').order('title asc').limit(resultsLimit) as results %}

Total results:{{ paginate.total }}

{% set total =  craft.entries(filterParams).section('object').order('title asc').total() %}
{% set count =  craft.entries(filterParams).section('object').order('title asc').count() %}


texts:
We are using the Craft's currency filter to display localised prices 344552.32 | currency('GBP') which works great in most instances.

However the currency symbol for UK Sterling in the French locale file is £UK and the translation company we are working with are saying that we just need to output £.

This is defined in the currencySymbols array of craft/app/framework/i18n/data.fr.php.

Is there a way we can affect that at a configuration level or at runtime? If not I guess we would have to create our own filter function that wraps the core functionality and does a string replace on the output.


texts:
After I input my credentials, it just stayed on the login page, and did not go to the dashboard. The password is good, we didn't get invalid username and password error.

I opened the trace mode and found this error in the craft.log:

  Unable to determine if PATH_INFO is enabled on the server: [curl] 60:
  Could it cause the error?

  The CSRF token could not be verified

2016/12/20 12:52:41 [error] [exception.Craft\HttpException.400] exception 'Craft\HttpException' with message 'The CSRF token could not be verified.' in /var/www/vhosts/xxx.com/master/craft/app/services/HttpRequestService.php:1314 Stack trace:
    #0 /var/www/vhosts/xxx.com/master/craft/app/framework/base/CComponent.php(561): Craft\HttpRequestService->validateCsrfToken(Object(CEvent))
    #1 /var/www/vhosts/xxx.com/master/craft/app/framework/base/CApplication.php(212): CComponent->raiseEvent('onBeginRequest', Object(CEvent))
    #2 /var/www/vhosts/xxx.com/master/craft/app/framework/base/CApplication.php(183): CApplication->onBeginRequest(Object(CEvent))
    #3 /var/www/vhosts/xxx.com/master/craft/app/index.php(62): CApplication->run()
    #4 /var/www/vhosts/xxx.com/master/public/index.php(20): require_once('/var/www/vhosts...')
    #5 {main} REQUEST_URI=/wtuygyq/upuj/duhuhog


texts: Update checkbox value through plugin (Craft 3)

texts:
I'm trying to update a checkbox field of an entry through a plugin service. I tried two things:

Get the field values with $entry->fieldHandle->getOptions(), then manipulating the resulting array, then set the value with $entry->fieldHandle->setOptions()

$contact = Entry::find()
    ->id(...)
    ->one();
$newsletters = $contact->contactNewsletterSubscriptions->getOptions();
$newsletters[$index]->selected = false;
$contact->contactNewsletterSubscriptions->setOptions($newsletters);
Craft::$app->elements->saveElement($contact);

(where $index is the array index of the setting I want to change)

-> this didn't work (no error message, changes just didn't get saved)

If I make a var_dump of $contact, the field contactNewsletterSubscriptions is showed as string. I played around with json_decode and serialize to get the right formatting (it looks exactly as when doing a var_dump):

$newsletterSubscriptions = json_decode($contact->contactNewsletterSubscriptions->serialize());
$index = array_search($newsletterName, $newsletterSubscriptions);
unset($newsletterSubscriptions[$index]);
$contact->contactNewsletterSubscriptions = (string)json_encode(array_values($newsletterSubscriptions))

-> doesn't work either; value gets saved as string; if I later call getOptions() on the field I'm getting "Call to a member function getOptions() on string"

Any idea how I can change the status of a checkbox from selected = true to selected = false?

Best regards.


texts: Grabbing an asset field from Page A to display on Page B

texts:
I'm trying to display an asset that the client has selected to show up on the main page, and have it display on a totally different page. This sounds simple but I keep getting errors (and im learning).

Main page asset:

{% for asset in entry.donateHeaderImage %}
   <img src="{{ asset.url }}">
{% endfor %}

Not sure how to display that asset on a different page in Craft.


texts:
I have a Craft site which seems to function properly but I see a 404 in the header http status code. I’ve located the following in the error logs:

2016/07/28 15:22:30 [error] [exception.Craft\HttpException.404] exception 'Craft\HttpException' in   /var/www/touchtunesmedia.com/craft/app/controllers/Templat$
Stack trace:
#0 [internal function]: Craft\TemplatesController->actionRender('home', Array)
#1 /var/www/touchtunesmedia.com/craft/app/framework/web/actions/CAction.php(109): ReflectionMethod->invokeArgs(Object(Craft\TemplatesController), Array)
#2 /var/www/touchtunesmedia.com/craft/app/framework/web/actions/CInlineAction.php(47): CAction->runWithParamsInternal(Object(Craft\TemplatesController), Obje$
#3 /var/www/touchtunesmedia.com/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#4 /var/www/touchtunesmedia.com/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#5 /var/www/touchtunesmedia.com/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#6 /var/www/touchtunesmedia.com/craft/app/framework/web/CWebApplication.php(282): CController->run('render')
#7 /var/www/touchtunesmedia.com/craft/app/framework/web/CWebApplication.php(141): CWebApplication->runController('templates/rende...')
#8 /var/www/touchtunesmedia.com/craft/app/etc/web/WebApp.php(288): CWebApplication->processRequest()
#9 /var/www/touchtunesmedia.com/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#10 /var/www/touchtunesmedia.com/craft/app/index.php(62): CApplication->run()
#11 /var/www/touchtunesmedia.com/public/index.php(19): require_once('/var/www/toucht...')
#12 {main}
REQUEST_URI=/

I have a home partial which is rendering fine so I’m having a hard time diagnosing where the error may be stemming from. Additionally everything returns a 200 status code in my network profiler other than the request for the document.

If I change the public dir’s index.php to echo test there is no 404 in the header status code. If I change my main layout template to a basic html file with nothing in it I get a 404 in the status code.


texts: Can I query based on a date field rather than the postdate?

texts:
I'm passing along a year as the yearQuery variable.  Later in my template, I am doing this:

{% set eventEntries = craft.entries
    .section('events')
    .eventStartDate('>=' ~ yearQuery)
    .eventStartDate('<' ~ (yearQuery + 1))
    .orderBy('eventStartDate asc')
    .limit(12)
%}

What I want to do is show all entries for a year based on the "eventStartDate" field - and not the date they were posted.

So basically, all Events that were on in 2018, etc.

Is it possible to do this within this query or is there something I am just missing since I have been up way too late?  I have a feeling I may be missing something obvious...


texts: Craft 3 plugin to import channel entries

texts:
I try to finish a plugin which imports data into my craftcms project. I already created a console based method/service, which I trigger/run in my shell. Inside my method(s) I receive data (XML or JSON) I parse my data and try to create and fill an entry of a specific channel I already created.

I tried "saveElement()" which doesn't work.

I found some tuts and informations for craftcms v2 (for example: https://docs.craftcms.com/api/v2/craft-entriesservice.html#public-methods)

Now i am stuck and i can not find any informations on how to solve this with craftcms v3.

Here is my last version of code after hours of different trys :(

$section = Craft::$app->sections->getSectionByHandle('testentry');
$entryTypes = $section->getEntryTypes();
$entryType = $entryTypes[0];
// Save Entry
//$entry = new EntryModel();
$entry = new \craft\elements\Entry();
$entry->sectionId = $section->id;
$entry->typeId = $entryType->id;
//$entry->locale = Craft::$app->i18n->getPrimarySiteLocaleId();
//$entry->authorId = 1;  // TODO:  Set author
$entry->enabled = true;
$entry->postDate = $post['post_date'];
$entry->slug = $post['post_name'];
//      $entry->getContent()->title = $post['post_title'];
//      $entry->setContentFromPost(array(
//          'body' => $postContent,
//          'categoryCareer' => NULL,
//      ));

if (Craft::$app->elements->saveElement($entry)) {
    $result = true;
}
else {
    echo 'Could not save the Job entry.'."\n";
    $result = false;
}


texts:
I’m a would-be first-time Craft user. I’m trying to set up a first trial site but not having much success.

I’ve been trying to install Craft CMS on my host provider’s server. I use SmartHosting/Krystal as hosting provider.

I’ve gone through the install instructions and get as far as step three. On step three it blinks on ‘Installing Craft CMS’ for about half a second before changing to ‘Oops.’  With the circular timer beneath, it just stays on this “forever”.

When I search for this issue, there are quite a few mentions of this being a problem with Dreamhost (hosting service provider) so I have taken this up with my service provider in case it’s a similar issue. They have tried the same installation procedure on my behalf and get the same problem.  Their last reply to me is as below.

Can you help me solve my install problem?

+++++

Having spent some time on this for you I'm not entirely sure what's causing this issue. the CraftCMS system isn't outputting any PHP errors and I can't see any errors on the server logs either. Progressing this I'd have to recommend reaching out to craftcms support to find out if there's any known issues or if they can assist in debugging this issue for you.

++++

PS One possibility is that the install did work after all and the oops message is erroneous. Is there a simple way to find out if it did in fact work OK?


texts:
I was just checking out the AP insights case study:
I came across the LiveView Editor screenshot. I see an inline Image Transform Crop field. What is the method to add this crop field ?


texts: Possible to append another field to entries field title?

texts: Does anyone know of a way to append another field to the entry title displayed in an entries field? I'd like to try and append an entry_version field to the title displayed so I get something like "Entry Title - v1" instead of just "Entry Title" when selecting related entries in a parent entry.


texts: PHP Error log in CP gives me 403 forbidden

texts:
If I want to view the PHP Error logs from craft true utils/logs I get an 403 Forbidden error.

nginx/1.6.2

../admin/utils/logs/phperrors.log

What could be wrong?


texts: Commerce: reading Stripe object in Craft Transaction model

texts:
I'm looking to add the credit card last four digits to my customer's frontend order history.  Stripe is the gateway.  The Stripe transaction object doesn't seem to be available in the Craft Transaction object (the documentation seems to be in line with this).

However, in the Commerce CP under Orders, I have see the full Stripe object in the Transactions box and it does have the last4 property that I'm looking for.

Is there any way to bring that info to the twig templates?


texts: Anyone know how to utilise the getActivePageIdForLevel function that AM Nav (https://github.com/am-impact/amnav) now has? Would really like to be able to have a secondary menu on a page which just has the navigation items that are for that current section. Can't see how to use it in the Docs though?


texts: Allow anonymous submission on a custom element type?

texts:
I have a custom element type that I want to allow anonymous submission from the front-end. I have a solid concept on how the form data is passed but I seem to be missing something.

I have the controller setup like so:

class PluginNameController extends BaseController
{
    /**
     * @var Allows anonymous access to this controller's actions.
     * @access protected
     */
    protected $allowAnonymous = array('actionSubmit');

    /**
     * Allow public submission of the element type
     */
    public function actionSubmit()
    {
        // require post request for this action
        $this->requirePostRequest();

        $entry = craft()->request->getPost();

        // set the form id from the post request
        $formId = craft()->request->getPost('formId');
        $entry = craft()->request->getPost();

        // if form id is empty, throw exception as we can't continue
        if (!$formId) {
            throw new Exception(Craft::t('The formId is required to submit.'));
        }

        if (craft()->pluginName->publicSubmission($formId, $entry))
        {
            $this->redirectToPostedUrl();
        }
        else
        {
            die('failed submission');
        }
    }

My element type has 4 fields that are required and those submit anonymously as expected as I am grabbing them using getPost. However, my plugin also utilizes the getSources method and each formId has a field layout assigned to the custom element type, lets say 'entry'.

Whats causing the trip up is the fact that since this is an element type that utilizes a field layout, I will need to account for the fields based on the formId. So when using getPost I can namespace the attributes for the element type, but I am trying to find the best way to capture the fields specified in the field layout and save those to the appropriate table..

Any thoughts?


texts:
This is a beginner question:

How do I create a link to an entry using entry's id?

I tried several combinations, such as {{ entry.getUrl(my_id) }}, {{ entry.url.id(my_id) }}, etc. but failed to found the correct syntax.


texts:
I like to have the user’s full name in their profile page-url rather than the username in case they don’t want their username associated with their full name. In my case they don’t get to set the username at the sign up point but might been asked for a username by the person signing them up.

So, how do i use the user’s full name as an identifier in the url of their profile page?

Like so: example.com/user/first-last

Is that even possible?


texts: Upload Error: 403 Forbidden response with DigitalOcean

texts:
This is the error I get when uploading files through the front end and Craft admin into a docs folder on my DigitalOcean s3 instance (bucket name is changed to test).

Error executing "ListObjects" on "https://test.ams3.cdn.digitaloceanspaces.com/?prefix=content%2Fdocs%2F&delimiter=%2F&encoding-type=url"; AWS HTTP error: Client error: GET https://test.ams3.cdn.digitaloceanspaces.com/?prefix=content%2Fdocs%2F&delimiter=%2F&encoding-type=url` resulted in a 403 Forbidden response: AccessDeniedtesttx0000 (truncated...) AccessDenied (client): - AccessDeniedtesttx0000000000000199322ec-005cdc1c7b-10e1ef4-ams3a10e1ef4-ams3a-ams3`

What does this error mean?

I wondered if it was an issue with the CDN settings? After I noticed images were loading in slowly I began using the following in my config for DigitalOcean - which loads in images faster. Then I noticed that I can no longer upload files through front end forms into volumes set up with DigitalOcean. Also some of my templates are not using the full path referencing the cdn...

'SPACES_API_KEY' => 'XXXXXXX',
'SPACES_SECRET' => 'XXXXXXX',
'SPACES_ENDPOINT' => 'https://ams3.cdn.digitaloceanspaces.com',
'SPACES_REGION' => 'ams3',
'SPACES_BUCKET' => 'test',
'SPACES_URL' => 'https://test.ams3.cdn.digitaloceanspaces.com',


texts: URI with multiple URL formats (after slug)

texts:
Is it possible to have a URI like this: /artist/{slug}/news
to create an overview of all news articles of this particular artist?
I tried to set it up with Routes and with a section Entry URI, but I get a 404


texts: How can I get a field's value from a global based on a url segment?

texts:
I have a rich text field with a handle of myTextField that I have included in a global set called firstGlobalSet.

What If I created another global set called secondGlobalSet and included the same field myTextField.

How could I get the correct field from the correct global set based on url segment?

For example, mysite.com/first or mysite.com/second


texts:
I'm creating field names for electrical components and I'd like to use subscripts like this:

Vmin
Vmax
Vadj

Vmin
Vmax
Vadj

Note that this is just for the field name, not the handle. Is there a way to do this in Craft, or a plugin that provides this functionality?

Notes:

Unfortunately, Unicode characters won't work in this case because the latin characters I need are not all available as subscripts in Unicode.
I've tried the Relabel plugin without success.


texts: How do I control order of output using Seomatic plugin

texts:
When I use the {% hook 'seomaticRender' %} tag in my template, I expected that it would output the data in the position where it's located. For example, I have the following in my template:

{% hook 'seomaticRender' %}
<meta name="msapplication-TileColor" content="#ffffff">

But when the template is rendered, the Seomatic data is output after the "msapplication-TileColor" meta tag. I don't suppose it matters much, but I like to keep a specific order for tags in my header.

I'm quite sure the answer is somewhere in the documentation, but it would be great to have a comprehensive example template.


texts: Get related variants from entry and then show products for related variants and then loop only the variants that are related in commerce

texts:
Struggling with this one. If anyone can help me...?
I have a section of entries called Vehicles.
In this I have a related Variants field type. This has many different variants that related to each vehicle.
On each vehicle page, I want to loop through the main products that are related by their variants but then loop through and only show the related variants that are link to the vehicle.
As an example.
I have a vehicle that has the following related variants.
Product A - Variant 1
Product A - Variant 2
Product A - Variant 3
(product A also has variant 4, 5 and 6)
Product B - Variant 2
Product B - Variant 3
Product B - Variant 6
(product B also has variant 1, 4 and 5)
On the vehicles page. I want to show products A and products B with a list in each showing the related variants. So as per the example. Product A -  would show Var1, 2 and 3 and Product B - would show Var2, 3 and 6.
Here is some code I have as a starting point:
{% set selectedVehicle = craft.entries
  .section('vehicles')
  .id(vehicle)
  .with( [
    'relatedVariants',
    'vehicleBrand',
    'oemFixings',
    'afterMarketFixings'
  ])
  .one() %}

{% set variantsQuery = selectedVehicle.relatedVariants %}
{% set variants = variantsQuery.all() %}

{% set wheelSpacers = craft.products
  .type('wheelSpacers')
  .hasVariant(variantsQuery)
  .orderBy('title ASC')
  .all() %}


texts: Sort variants by product (not variant) field?

texts:
Is it possible to get variants ordered by product (not variant) field?
I have tried following without success:
craft.variants().orderBy('productField asc').all();
craft.variants().orderBy('product.productField asc').all();
craft.variants().orderBy('commerce_products.productField asc').all();


texts: Index "Column A" for unique values, then recursively group "Column B" values based on those uniques

texts:
I have two levels of product variants in a table field. If the product uses Secondary Variants, I need a way to search the Primary Variants column for unique values, then output individually grouped Secondary variants.

Both Primary and Secondary Variants are unique for each product.

Is there a way to do this with TWIG/Craft templates? If not, what do you recommend? Query JSON? Plug-in?


texts: Error while sending QUERY packet in continuously running process

texts:
I'm using php-resque + Redis to get queues/workers into Craft, and so far I've managed to get it all running.

My test worker looks something like this:

<?php
namespace Craft;

class JobHandler
{
    public function perform ()
    {
        $criteria          = craft()->elements->getCriteria(ElementType::Entry);
        $criteria->section = 'products';
        $criteria->limit   = 20;
        $entries           = $criteria->count();

        if ( $entries ) {
            ElasticSearchPlugin::log("Found! $entries entries", LogLevel::Info, $force = true);
        }
    }
}

When I add a job to the queue, the worker successfully runs the perform() method, and it shows up in the console and log.

However, all jobs after the first fails consistently, with the following stacktrace:

2016/11/10 10:49:25 [error] [php] Error while sending QUERY packet. PID=80844 (/src/craft/app/framework/db/CDbCommand.php:508)
Stack trace:
#0 /src/craft/app/framework/db/CDbCommand.php(396): Craft\DbCommand->queryInternal()
#1 /src/craft/app/services/FieldsService.php(251): Craft\DbCommand->queryAll()
#2 /src/craft/app/elementtypes/BaseElementType.php(445): Craft\FieldsService->getAllFields()
#3 /src/craft/app/elementtypes/BaseElementType.php(463): Craft\EntryElementType->getFieldsForElementsQuery()
#4 /src/craft/app/services/ElementsService.php(665): Craft\EntryElementType->getContentFieldColumnsForElementsQuery()
#5 /src/craft/app/services/ElementsService.php(528): Craft\ElementsService->buildElementsQuery()
#6 /src/craft/app/models/ElementCriteriaModel.php(385): Craft\ElementsService->getTotalElements()
#7 /src/craft/app/models/ElementCriteriaModel.php(174): Craft\ElementCriteriaModel->total()
#8 /src/craft/plugins/queue/handlers/JobHandler.php(23): Craft\ElementCriteriaModel->count()
#9 /src/craft/plugins/queue/vendor/chrisboulton/php-resque/lib/Resque/Job.php(182): Craft\JobHandler->perform()
#10 /src/craft/plugins/queue/vendor/chrisboulton/php-resque/lib/Resque/Worker.php(241): Resque_Job->perform()
#11 /src/craft/plugins/queue/vendor/chrisboulton/php-resque/lib/Resque/Worker.php(203): Resque_Worker->perform()
#12 /src/craft/plugins/queue/consolecommands/JobCommand.php(85): Resque_Worker->work()
#13 unknown(0): Craft\JobCommand->actionWork2()
#14 /src/craft/app/framework/console/CConsoleCommand.php(172): ReflectionMethod->invokeArgs()
#15 /src/craft/app/framework/console/CConsoleCommandRunner.php(71): Craft\JobCommand->run()
#16 /src/craft/app/framework/console/CConsoleApplication.php(92): Craft\ConsoleCommandRunner->run()
#17 /src/craft/app/framework/base/CApplication.php(185): Craft\ConsoleApp->processRequest()
#18 /src/craft/app/etc/console/yiic.php(81): Craft\ConsoleApp->run()
#19 /src/craft/app/etc/console/yiic(4): require_once()

in /src/craft/app/etc/console/ConsoleApp.php (265)
in /src/craft/app/services/FieldsService.php (251)
in /src/craft/app/elementtypes/BaseElementType.php (445)

After googling, most suggestions hover around adjusting max_allowed_packet and/or wait_timeout. This doesn't make sense to me. I've set max_allowed_packet to 512M, and wait_timeout defaults to 8 hours.

Any ideas?

Is CDbCommand not cleaning up after it self because the process runs forever?


texts:
I'm working on a plugin called modelselector and I want to use a template stored in the plugin templates folder but it should be shown on the front-end of the website.

Currently the following direct URL works for me:
actions/modelSelector/showSelection/40c86a9b-53ec-43f4-8e8b-7c77ee0a13f5

I also set up a site route like so:
'modelselector/(?P<selectionUid>[^\/]+)' => array('action' => 'modelSelector/showSelection')

However when I go to: modelselector/40c86a9b-53ec-43f4-8e8b-7c77ee0a13f5 I get the error: Unable to find the template “modelselector/show”..

I did some research and found that I need to set the template mode using: craft()->templates->setTemplateMode(TemplateMode::CP);. But this doesn't seem to work for me. It still can't find the template when the TemplateMode is on CP or Site.

Any ideas?


texts: Processing Business Logic on user.saveUser

texts:
I have the following code in my plugin.

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

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

    // only fire if new user
    if ($event->params['isNewUser']) {

        // business logic
        // how do i save result to custom user fields etc...

    }
 });
}

I guess my question is whether the userRecod has already saved at this point? If so do I need to create another user object, make changes and call .save again? Or is the user still available to me?


texts: How to display all fields belonging to current entry?

texts: How do I modify a template to include a loop that displays all custom fields that I added to the field group that the current entry belongs through? I know how to display the fields individually by calling their name, but how to display all fields belonging to the group?


texts: How to order or filter entries by their author's custom field?

texts:
Is it possible to order and/or filter all entries from a section whose author has a custom field value that is set to "X"?

Below is the starting code.

in Twig:

{% set elementQuery = craft.entries()
    .section('sectionHandle')
    .with(['author'])
%}

in PHP:

$elementQuery = Entry::find()
    ->section('sectionHandle')
    ->with(['author']);


texts: Why does MultiAdd think I am not sending any items?

texts:
I am trying (and failing miserably) to send multipule products to my cart using MultiAdd

I can see the data getting sent - it looks ok? I get a 200 response back, so I know its working, but I'm always getting this error:

{"error":["No items?"]}

Here is what my form data looks like:

action:multiAdd/multiAdd
redirect:commerce/cart
qty:1
CSRF:gQBSJxqkMIQChG3r6TJ4Dz81dgtZuh4yrv_ZUDTp|ecc547c00a45b29a506b9f4c7904e62add62d37a
myProductOne:174
myProductTwo:64
myProductThree:189

My product template looks like this:

<form>
<input type="hidden" name="action" value="multiAdd/multiAdd">
...

<select name="myProductOne">
    <option value="174">Value</option>
</select>
...
<select name="myProductTwo">
    <option value="64">Value</option>
</select>
...
<select name="myProductTwo">
    <option value="189">Value</option>
</select>

I am using jquery validator to validate my form; I'm handling the submit like this:

...
 onFormSubmit(function (response) {
     console.log(response);
 });

var onFormFormSubmit = function (callback) {
    var data = $('#campRegistrationForm').serialize();
    data['CSRF'] = $('input[name="CSRF"]').val();

    $.ajax({
        'type': 'post',
        'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
        'cache': false,
        'data': data,
        'url': '/actions/' + $('input[name="action"]').val(),
        'dataType': 'json',
        'timeout': 50000
    }).done(function (response) {
        callback(response);
    }).fail(function (error) {
        // Total fail.
    });
};

I see on the plugin's page, I need to have markup like this:

<select name="items[{{ loop.index }}][options][color]">

I believe it all boils down to the fact I'm not doing this correctly:

{% for product in craft.commerce.products.find() %}
...
{% endfor %}

Since I am selling 3-5 different products on any given page, I can't loop through all of my products as I only need specific ones at any given time. I'm not sure how to set that up correctly.

EDIT

Thank you so much!

To help others, here is what each of my select input(s) look like:

<select id="myProductOne" name="items[1][purchasableId]">
<input type="hidden" name="items[1][qty]" value="1">
...
<select id="myProductTwo" name="items[2][purchasableId]">
<input type="hidden" name="items[2][qty]" value="1">

...


texts: Why can't I log in anymore when I change primary site manually in database?

texts:
Because of a bug (https://github.com/craftcms/cms/issues/7657), I got locked out from admin because no site seemed to be marked as primary in the DB, even though one of the site files clearly had a primary:true setting.
This is using latest craft as of writing, 3.6.9.
Changing the primary site directly in the sites-table will cause the problem (WEIRD!), logging me out and refusing to log me in again. This doesn't happen in my dev environment when switching the primary site, so I'm not sure what's up here...


texts: Filter events by owner fields - Calendar plugin

texts:
I'm using Michael Rog's Craft Calendars plugin.

I'm wondering if it's possible to limit events to specified owner category.

For example, I have a training entry with trainingType and trainingLevel category type fields.

While listing events is it possible to do something like:

{% set params = {
    calendar: 'myAwesomeCalendar',
    dateRangeStart: 'today',
    dateRangeEnd: now|date_modify("+1 month"),
    owner.trainingType = 'webinar',
    owner.trainingLevel = 'expert'
} %}

{% for e in craft.calendars.events(params) %}

{{ e.owner.title }}

Starts: {{ e.startDate  | date("Y-m-d") }}

{{ e.owner.trainingType }} , {{ e.owner.trainingLevel }}
{% endfor %}

If not, how else would you approach this.


texts: Updating large database from Craft 2 > 3 via command line

texts:
I'm migrating a large Craft + Commerce site up to Craft 3. I've completed all the initial steps and get as far as the "To complete the update, some changes must be made to your database. Finish up" message.

The first time I tried this it timed out, so I used the ./craft migrate/all to perform all the database updates. This worked well - not surprised it timed out over http given the amount it has to do!

Problem is when going back to the Admin URL I still get the database message, if I click Finish up it still times out, I guess it is trying to reapply the migration.

Is there a way to let the Craft install know I have already done this?

Thanks


texts: Detect if it is a new user or not in PHP

texts:
I have been developing some plugin code for my registration form in Craft 3.

The event will be EVENT_AFTER_SAVE_ELEMENT, but I do not know how to detect if it is a new user or not.
In Craft 2, the way was if ($event->params['isNewUser']).

It would be grateful for me if someone tell me how to do it.


texts:
I have an account page for all my users, however i'm running into a small issue with being able to update passwords / emails on the frontend. Any advice on how to do this? I read that updating either of those fields would require checking and verifying the change in your email.

Thanks


texts: Redactor image caption not saved and formatting lost

texts:
In Craft CMS 2.6.2945, I've added the "image" button in the Redactor config.  In the editor, I've added an image and added a caption (by clicking the inserted image).  When the image is saved, the caption shows up properly and I could see that it was set as figure/figcaption tags after inspecting it.

However, after saving the entry (save and continue editing doesn't even work now as it takes you to the Entries page), the formatting gets lost and the image ends up in a p tag, followed by the caption in a p tag in the editor, but in no tags in templates as raw html.

Is anyone using captions and having troubles?

Added the following comment:

  After some more testing and debugging, I'm noticing that Redactor is
  outputting malformed HTML. The img is going in a p tag, following by a
  figcaption tag. Since my rich text field was set up to clean malformed
  HTML, saving the entry would get rid of the orphaned figcaption tag.
  Any ideas why the img is not going in a figure tag?

Edit: here's the JSON:

I also turned off the HTML purify and clean options but that didn't work out.

{
    "buttons": ["format","bold","lists","link","file","image"],
    "plugins":["video","source"],
    "toolbarFixed": true,
    "formatting": ["p", "blockquote", "h2", "h3", "h4", "h5", "h6"],
    "formattingAdd": {
        "para-intro": {
            "title": "Paragraph Intro",
            "args": ["p", "class", "intro", "toggle"]
        },
        "caption": {
            "title": "Caption",
            "args": ["p", "class", "cap"]
        }
    }
}


texts: onBeforeDeleteCategory not working / inconsistent

texts:
I need to run checks before allowing a user to delete a category. I have added the following code to my main plugin class:

craft()->on('categories.onBeforeDeleteCategory', function(Event $event) {
    $event->performAction = false;
});

This is just to test it. I expect this to cause any category delete functions to fail because I'm explicitly setting the event perform action property to false.

There are two problems:

No. 1 - This code only runs when I click into the category and then press the delete button. If you do it from the action menu in the category list this event is not even fired. This seems like a bug to me.

No. 2 - This code, even when executed, does not prevent the category from being deleted. Even though I set $event->performAction = false it still just deletes the category.

Any ideas?

EDIT:

I did some sleuthing regarding #1 and I found out that I have to call the event like this:

craft()->on('elements.onBeforeDeleteElements', function(Event $event) {
    $event->performAction = false;
});

However I'm still running into #2 on both instances where setting performAction to false does not prevent the action from completing... :(

Edit 2
It looks like there is no condition for performAction after the event is fired so there appears to be no way to stop a delete event via an event. Is this the case?


texts:
I'm trying to output a list of Brand names grouped by first letter. But some items have a number or symbol in the name. I want to list first the Numbers and symbols under 0-9 and the rest of the brands under A-Z

Like this:

0-9

+People
10 Days
2Two
40 Weft
55 DSL
81hours

A

Acne
Adidas

B

B.Young
etc etc.


texts: Find entries related to user and display field name

texts:
If I’m finding all the entries that are related to a user, how could I get the field handle that the found user is referenced from?

{% set events = craft.entries.section('events').relatedTo(user) %}
{% for event in events %}

  {# What goes here? Hypothetical code based on non-existent method would be: #}

  {% set field = craft.fields.relatedTo(user) %}
  {{ field.title }}

{# Obviously this isn't possible. Any way to accomplish something like this? #}

{% endfor %}

There are multiple users fields in the found entries, and there will be different logic depending on which field the user is found.


texts: Trying to figure out how to get the "name" and "handle" of an asset volume, given the volume ID. Tried all the obvious things, no luck!


texts: Looping Entries in Super Table, display row details

texts:
I have a Super Tables field, containing related entries:

I'd like to display the field name (ie 'English Links') in a template, but can't figure out how, the following outputs a string of values and if I try to add a handle to the row output I get 'Impossible to access an attribute ("handle") on a string variable'.

{% for row in entry.relatedArticleLinks %}
    {{ row }}
{% endfor %}

I really don't think this was written very well in the first place tbh, as the rows are hard coded:

English

            {% for link in entry.relatedArticleLinks.englishLinks %}

{{ link.title }}

            {% endfor %}

I'm sure there's a better way of displaying this field which would allow new rows to be displayed automatically?


texts: How to duplicate entries and loop them without getting a Twig or deprecation error?

texts:
I'm trying to duplicate entries inside a macro, which will displays duplicated items inside a carousel.

It's not possible to merge Element Queries. Even if it's possible to merge IDs, merging an array of IDs will end up with non-duplicated entries.

This is how I duplicate entries:

{% set entries = entries | merge(entries) %}

After that, this is how I loop, and the resulting issue:

for entry in entries.all()

→ Twig error: Impossible to invoke a method ("all") on an array;

for entry in entries

→ deprecated warning: Looping through element queries directly has been deprecated. Use the all() function to fetch the query results before looping over them;

for entry in entries.all() ?? entries or entry in entries ?? entries.all()

→ same warning as previous point;


texts: Front End Entry Form - Proper Syntax for Custom Fields

texts:
I'm working on a front-end entry form with custom text input fields. From the Entry Form knowledgebase docs, I read "Any custom field handles must be provided in a fields[] array like body is above." On that page their example 'body' field is a textarea field, and when I use this with my own textarea fields it works fine. However I'm having trouble formatting that same logic to make a simple plaintext input field work properly.
My current (non-working) code is:
 <label for="contactName">Contact Name</label>
  {{ input('text', 'contactName', entry.contactName, {
    id: 'contactName',
    name: 'fields[contactName]'
  }) }}

No errors are being thrown when I submit the form, but the values from the plaintext input area are not being saved. What's the proper way to format such that the input values are saved properly?


texts:
I'm writing a plugin for Craft Commerece that performs action on commerce_orders.onOrderComplete

I need to check the value of product custom field (Matrix) in order to determine action parameters.

I tried to use $lineItem->purchasable->product->myCustomFieldHandle, but this returns me ElementCriteriaModel without any data entered for product in this field.

Any ideas on how to get actual data saved in custom field for product?


texts: JS POST setting new password with save-user re-submission not working with returned CSRF token

texts:
I have an AJAX form that sets a new password (using users/save-user) for the current logged in user (not an admin).  It works for the first time but when I re-submit with the new token, a 400 Bad Request error is returned.  Here are the 2 requests:
POST Header (first time):
CRAFT_CSRF_TOKEN: <token obtained on page load via {{ craft.app.request.csrfToken | e('js') }}>
action: users/save-user
currentPassword: <current password>
newPassword: <new password>
userId: <id>

Post Response (first time):
csrfTokenValue: <new token>
id: <id>
success: true

POST Header (second time):
CRAFT_CSRF_TOKEN: <new token (as obtained in the above response)>
action: users/save-user
currentPassword: <current password>
newPassword: <new password>
userId: <id>

Post Response (second time):
error: "Unable to verify your data submission."
exception: "yii\web\BadRequestHttpException"
file: "./craft/vendor/yiisoft/yii2/web/Controller.php"
line: 209
trace: <array>

I'm thinking I might need to update the CSRF browser cookie but can't find anything documented.  Can anyone help?
Thanks!


texts:
I have a Craft CMS installed in a development environment thewebsite.test.

I can't get it to trial paid plugins and Craft Pro.

It appears Craft doesn't recognise it's in a development environment?

Application Info

PHP version  7.4.2
OS version   Linux 4.15.0-74-ubuntu
Database driver & version    MySQL 5.5.5
Craft edition & version  Craft Pro 3.4.6.1

I'm running Windows 10 with Vagrant/Homestead with Craft installed on a Virtual Machine in VirtualBox.

The same setup on a Mac does not have any issues with licensing.

I have copied the database and updated the .env file from the Mac install, and everything appears to be working except for the licensing issues.

Is there any way to force Craft CMS to recognise a dev environment?


texts: Assets (in assets folder) failing to load locally [Craft 2]

texts:
I'm trying to get my Craft 2 site running locally again (it worked at one point but now does not).
I have gotten all the db related issues (seemingly) done and dusted and the admin loads fine, but it seems that anything linked to Amazon S3 (or perhaps the {{ craft.config.rootUrl }}?) seems to be failing.
The devtools console has a lot of :
Failed to load resource: the server responded with a status of 404 (Not Found)
The local set up is using docker inside a virtual machine and is brought up using vagrant. I have all the code locally tied to lvh.me (on a specific port) and when the site loads, some external services (such as Imager) are still working – just nothing relating to aws / S3 for some reason.
Has anyone encountered this before? Have I forgotten to set something up re: Multi Environment variables or perhaps did Google change a policy that requires me to add permissions to the IAM user to allow for local access?
Thanks in advance for any steers.
Really at an impasse here. Can anyone help?
edit:
After helpful comments, I am getting the impression that since the path to the root of the Assets folder is something that is controlled by the general.php file and the files that aren't loading seem to be directly inside there (and local, as opposed to on S3), that maybe this isn't an S3 issue (yet). It seems that the local path to the Assets folder is least part of the problem.
Here's what my set up in general.php looks like:
// $protocol = isset($_SERVER['CRAFT_PROTOCOL']) ? $_SERVER['CRAFT_PROTOCOL'] : 'https';
$protocol = $_ENV['CRAFT_PROTOCOL'];
// force http on local environment
if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' ) {
    $protocol = 'http';
}

return array(
    '*' => array(
        'devMode' => false,
        'omitScriptNameInUrls' => true,
        'preserveImageColorProfiles' => true,
        'backupDbOnUpdate' => false,
        'generateTransformsBeforePageLoad' => true,
        'maxUploadFileSize' => 33554432,
        'environmentVariables' => array(
            'baseUrl' => $protocol.'://'.$_ENV['SITE_URL'].'/',
            'basePath' => $_ENV['DOCUMENT_ROOT'].'/',
            'assetsUrl' => $protocol.'://'.$_ENV['SITE_URL'].'/'
        ),
        'rootUrl' => $protocol.'://'.$_ENV['SITE_URL'],
        'siteUrl' => array(
            'en_gb' => $protocol.'://'.$_ENV['HTTP_HOST'].'/',
            'ja_jp' => $protocol.'://'.$_ENV['HTTP_HOST'].'/'
        ),
    ),
);

Anything look out of place to anyone? The assets that won't load locally, via lvh.me, are in the *public > assets > folder (e.g. public> assets > js > app.js). They load fine in the staging environment, but just not locally.  It feels like either a Docker / CI issue relating to the Sandbox or just a config issue with the settings above.
The error is a 404 not found and that URL is reading:
http://lvh.me/assets/js/app.js?v=14
What do you think?


texts: Craft 3.1 no longer updates all entries on section save - workaround?

texts:
Craft 3.1 seems to have removed the functionality where if a section is saved, all entries in that section are re-saved.

This has broken a bunch of functionality that relies on this on a site I've built.

Is there a workaround? Even if it's building another plugin to somehow listen for a save section event (is there such an event) manually triggering the same thing?


texts:
Is it possible to output whole playlists in the videos plugin by Dukt?
I have looked through the docs, but cannot see any examples or mention of this. But in the back-end system there are playlists.


texts: Images missing from Entries, but still on server

texts:
Have a bit of an issue.

Recently, a site I work had its asset index rebuilt upon finishing for some reason all images associated to entries are now no longer attached. They are still on the server and in the database.

How would one go about linking these back-up as I don't fancy going through every entry to reassociate the image manually.

Thank you for your help.


texts:
I want to send an email if/when an entry is saved with a lightswitch switched on after previously being off.
I have the below code in my plugin's init file, but I don't know how to

check for the section uid and verify that it's the right section or

check the previous value and compare it to the value being saved.

    Craft::$app->elements->on(Elements::EVENT_AFTER_SAVE_ELEMENT, function(ElementEvent $e) {
            $element = $e->element;

        });

I'd appreciate any help, thanks.


texts: How to use the Element API plugin only when logged in?

texts: I want to use the Element API plugin, but the content must only be visible when users are logged in. How I do this for a section? Is it possible to use requirelogin or currentUser for this?


texts: Trying to set a dynamic twig variable using craft.request and a craft global

texts:
I'd like to understand how to combine these two elements into a twig set vars.

--

Context: I'm building a dynamic template that will list entries from which ever section the URL segment loads. For example /news will be news articles.

Each template will have a page title variable that I'm sending up to the _layout master. The page title's are input using craft.global's I have them setup like this {{ news.pageTitle }}.

In my dynamic template I'm trying to load everything from the URL slug. For example if it loaded the /notices URL the template would render the global: {{ notices.pageTitle }}.

--

Craft global: {{ news.pageTitle }}

URL Segment (/news): {% set getSegment = craft.request.getSegment(1) %}

This works: {% set pageTitle = news.pageTitle %}

But this doesn't: {% set pageTitle = getSegment.pageTitle %}


texts: Send email notification to admins when a new entry is created

texts: Anyone written a simple plugin that does this out there? When a user submits a form on the frontend, it creates a new entry (with the default status set to disabled). I'd like to set it up so that the admins receive an email notification every time a new disabled entry is created for that section.


texts: Why is the Craft without filter not working correctly and how to debug?

texts:
I am using the Dukt Follow plugin to return 2 arrays which both hold User objects, I am then using the without filter to remove users from the array which are considered friends. Friends are determined by using the intersect filter on the 2 arrays.

Everything works apart from the second without filter which does not work, and returns objects that are in the friends array.

{# Friends, Followers & Following #}
{% set userFollowing = craft.follow.getFollowing(user.id) %}
{% set userFollowers = craft.follow.getFollowers(user.id) %}

{% set friends = userFollowing|length and userFollowers|length ? userFollowing|intersect(userFollowers) : null %}
{% set following = userFollowing|without(friends) %}
{% set followers = userFollowers|without(friends) %}

Is there an obvious reason why this might not be working?
How is best to debug something like this?

I have checked the output of all the arrays and objects and they do appear to hold the data that they should.

Basic data stored in each array:

User Following:
Array: ["Craft\\UserModel: bencallaway","Craft\\UserModel: davidwearn","Craft\\UserModel: shorn"]

User Followers:
Array: ["Craft\\UserModel: bencallaway","Craft\\UserModel: davidwearn"]

Friends:
Array: ["Craft\\UserModel: bencallaway","Craft\\UserModel: davidwearn"]

Following:
Array: {"2":"Craft\\UserModel: shorn"}

Followers:
Array: ["Craft\\UserModel: bencallaway","Craft\\UserModel: davidwearn"]

Full variable output can be accessed here: http://cl.ly/2o292X3O2r0M


texts: Managing a large number of Variants in Craft Commerce

texts:
I'm currently building a site for a client who's products vary in price depending on the width / height selected. Essentially what this means is each product has around 70 possible variations, each with it's own price.

My initial idea was to inject some JS that would allow the client to manage the variants in a table that would automatically generate / update the variants based on the contents of the table. Unfortunately, as far as I can tell, there is no way to access the JS that manages the variants as it's all done in a self contained, anonymous class.

I also tried creating a custom Purchasable entry type that would let me dynamically set the price of the of the line item based off the selected width & height. The keyword there being tried. I'm still trying to get to grips with custom Entry Types, and trying to get it to work with Commerce on top of trying to get it to work at all has made me, well, somewhat less than successful.

Has anyone had any success with managing large numbers of variants, or does anyone know of a simpler way to achieve what I'm after?


texts:
Making first steps with Craft CMS, and it's great, but there is one thing i can't figure out:
When trying to add a new entry with a rather complex set of fields (including matrix) there is an error:

Failed to load Twig template "_includes/field", index "764771142": cache is corrupted.
in E:\craft\playground\vendor\craftcms\cms\src\templates_includes\field.html
line 17:

{% if instructions or input %}
    {% embed "_includes/forms/field" with {
        label: field.name|t('site')|e,
        translatable: translatable,
        siteId: siteId,
        required: (not static ? required : false),

Editing existing entries works fine.
Running 3.0.4
Clear Cache Tool has run, and i also delete the cache files in /storage. No custom field types.
Thanks for ideas.


texts: passing the search query into html title tag

texts:
I wish to show the search query inside the page template but my logic seems to be off and just shows {{ query }} as a string.

What's the best way to achieve this?

{% extends "_layout" %}
{% set query = craft.request.getParam('q') %}
{% set title = "Search results for: {{ query }}" %}


texts: Sort matrix blocks in admin by a field within the matrix?

texts: I have a Single that includes a matrix as a field. The matrix has an internal date field. Is there a way to sort the matrix blocks by the date field on the admin side to help manage the blocks?


texts:
I'm trying to limit the results to 5, but its returning all of the results instead. I am using the below code:

{% set options = {
  cache : false,
  query : {
    limit : 5
  }
} %}

{% set timeline = craft.placid.request('projectsLatestTrending', options ) %}

{% for tweet in timeline.data %}

{{ tweet.name }}

{% endfor %}

Thanks in advance for any help.


texts: Populating TAG page when using the kebab filter

texts:
I have a page that displays entries based on a specific tag. It works well until I apply the kebab filter.
Here's my link to the page:
{% for tag in tag %}

{{ tag.title }}

{% endfor %}

and my tags/tag.html page looks like this:
{% set tag = craft.tags.name(tag).first() %}
{% set entries = craft.entries.relatedTo(tag).order('title') %}
{% if entries | length %}
   {% for entry in entries %}
       Code here
    {% endfor %}
{% endif %}

The page populates all entries regardless of the tag once I apply the kebab filter. How can I fix that?
Thanks in advance.


texts:
I'm calling user photo's from my template, but it error's out when trying to obviously call a user photo which is empty. What I'm trying to achieve is

  if there is no user photo, use the default placeholder image craft supplies

The problem I'm having trouble getting to the bottom of is, how to access the default user photo?

    <img class="img-fluid rounded-circle" src="{{ entry.author.getPhoto().url }}" width="100" height="100" alt="{{ entry.author }} Picture">

Any help would be great


texts:
Is there a MSSQL support for Craft CMS?
Or any plugin that can help to connect to a MSSQL database?

Thank you!


texts: How do you iterate over Matrix field in a Craft 3 plugin?

texts:
$entry = Entry::find()->section('my_section')->relatedTo($entry)->all();
$entry['myMatrixField']; // What do I do with this??

I know there are tutorials about how to handle Matrix fields in plugins in Craft 2, but how do I do this in Craft 3?


texts: How to insert a Sprout Form into a new page in Craft CMS

texts:
I am a Wordpress guy, and I've been given the task of handling my companies Craft site.

I have been at this for hours, and can't seem to figure out how to get the damn form to appear on the page I created.

The one line of code thing does not work when I copy paste it.
I have no website data on my local device, so this is all browser-based.

I really have no clue where to go from here, and the boss expects results.
I have the form created in Craft, it is only a matter of figuring out how to make it appear.

Please help a major n00b. Thanks.

Edit: My form is named stlForm
When I say it's all browser based, I mean I can only edit as much as I can by logging in as an admin. I have no Local data, FTP to access that I know of (our web people are MIA).


texts: How to convert custom plugins to custom modules

texts:
I have 3 custom plugins that we had someone develop for us a while ago and I would like to convert them to custom modules.  Since plugins are based upon modules, I was hoping there might be a cookbook out there.  I don't think the plugins were built using standard plugin scaffolding.
Thank you!


texts: Include Global Set Variable in Print Delimiters

texts:
I have a site which has another group site - both use same templates but I want to include different phone number in the header of each.

I was wanting to use Global Set Variables to pull this information in.

It works fine in the execute delimiters but not in the print delimeters.

This works fine:

{% include "includes/#{ craft.config.siteCode }/head-constants" %}

Is there any way to include it within another variable like below:

{{ #{ craft.config.siteCode }Defaults.defaultTelephoneLink }}

This gives the Template Error: Unexpected character "#".


texts: Use the edited field label instead of the default label in the table headings

texts:
^ This is what I've edited the label to be

^ This is what shows as the table heading - Can it not show as 'Telephone'?


texts:
I know this is bad practice but it's just for dev sites and there's no easy way around it with our current hosting provider. Anyway, I have my craft folder next to my index.php and $craftpath set to:

$craftPath = './craft';

Still I get this error:

Could not find your craft/ folder. Please ensure that $craftPath is set correctly in /chroot/home/rizencre/rizenweb.com/html/terravant/index.php


texts: User Event before Login - check if user has password and logged in before

texts:
Is there a User Event before the authentication is fired?

I want to show a message if the user doesn't have a password yet and if it's his first login / check if he never logged in before - All in the frontend.

If so, send the activation / set password email.

So i tried the EVENT_BEFORE_VALIDATE

 Event::on(
            Users::class,
            Users::EVENT_BEFORE_VALIDATE,
            function (UserEvent $event) {

Which returns nothing.

And the EVENT_BEFORE_AUTHENTICATE event. This seems to what i am searching for. But it seems that the event only fires if the user already has a password. If the user never logged in / has no password it seems that this Event is never fired.

Event::on(
            User::class,
            User::EVENT_BEFORE_AUTHENTICATE,
            function (AuthenticateUserEvent $event) {
                dd($event);
            }
        );


texts: I believe I made a mistake by creating about 15,000 entries in a Structure section. It has caused a lot of problems and so I decided to start again with a Channel section instead. I tried deleting the old section to remove the entries but it crashes mysql. Does anyone know a way to remove entries and their content in the database?


texts:
I already learned how to create a task from this page but I would like to know how to run this task?
I'm creating a portal where users are allowed to give their votes and discuss several projects. Backend users can create different phases and declare a start and an end date and a few days before these phases end all members/participants of this phase should receive an email.
I know how to send the mail, I know how to create the task but I don't know how to start the task 1, 3 and 7 days before a specific date.
Do those steps run every single second?
public function runStep($step)
{
    $criteria = craft()->elements->getCriteria(ElementType::Category);
    $criteria->group = 'phase';
    if($criteria->count()){
        $phases =  $criteria->find();
        foreach ($phases as $phase){
            $now = time();
            $threeDaysBefore = $now - (60 * 60 * 24 * 3); //Seconds * Minutes * Hours * Days
            $OneDaysBefore   = $now - (60 * 60 * 24 * 1); //Seconds * Minutes * Hours * Days
            $endTime = $phase->phaseEndDate->getTimestamp();
            if($endTime == $OneDaysBefore || $endTime == $threeDaysBefore){
                 craft()->myplugin->sendMailToUser();
            }
        }
    }
}

Where do I activate the task? Do I run craft()->tasks->createTask(/*parameter*/) in my plugin init() function?
And my last question: how can I debug my function? In my chrome network tap I receive a taskInfo every second but I can't var_dump() something from my runstep function.
Thank you very much


texts: Manually passing page number to paginate tag

texts: {% paginate %} tag takes current subpapage number from url address. Can this behaviour be bypassed and page number be passed directly into {% paginate %} tag?


texts: Dynamics Nav 2015 (Navision) integration

texts:
I'm looking for advise and a strategy for integrating Dynamics Nav 2015 with Craft Commerce.  I realise this is a broad question and a hard one, certainly since Craft Commerce has only been recently released.

One of the most important parts is that the integration from user perspective should be a fluent as possible:

(Live) Get prices and stock level
(Live) Get custom prices based on customer group and volume discounts
(Batch) Get Product catalogue (both products and categories)
(Batch) Get Product variants
(Batch) Get all product details (like measurements, custom properties)
(Live) Post basket to calculate total pricing (based on eg applicable taxes)
(Live) Post new customers and contacts
(Live) Get customers and contacts
(Live) Post new orders
(Live) Get orders and its details
(Batch ? Live) Get invoices and its details
(Live) Get address information (shipping / invoice)
(Live) Post Address information (shipping / invoice)

Other important parts are:

How to deal with user accounts: The navision contact on the same level as the user in craft.  But how would you deal with the creation of it, given that a user can created starting from both sides (from the web as a new contact in navision, from navision and later from the web as an existing contact).  All contacts / users need to be linked to a company object in Nav (again already existing in Nav or completely new)
Would it be possible to use queueing from Craft, to eg store orders that are taken when the Navision is not available.  Same goes for pricing info ,etc

I would be very interested to see

your general thoughts about the above
is it doable to have craft commerce that tightly integrated (what are other pitfalls I didn't think about)
if there is anybody who already started a similar challenge


texts: Craft Commerce: Detecting & Styling Flash Messages?

texts:
I'm styling my flash messages in Craft Commerce - I added if statements to detect the type of flash message. I noticed however that the message no longer displays but the styling does get picked up. Any ideas what I might need to do here?

{% if craft.session.getFlash('notice') %}

      {{ craft.session.getFlash('notice') }}
      &times;

{% endif %}

{% if craft.session.getFlash('error') %}

      {{ craft.session.getFlash('error') }}
      &times;

{% endif %}


texts:
I'm trying to target the first matrix block and changing the structure of the HTML, but nesting an IF statement within the loop but it's actually not doing anything, instead it's just displaying both the same.

{% for block in entry.contentMatrix %}
{% if entry.contentMatrix.first %}

          {{ block.contentTitle }}

        {{ block.contentDescription }}

  {% else %}

          {{ block.contentTitle }}

        {{ block.contentDescription }}

{% endfor %}


texts: Is there a way to programatically add a user when no one is logged in

texts:
In my controller, I can add new users when a user with the right privileges is logged in via craft()->users->saveUser(), but this doesn't work when no user is logged in.

Is "users/saveUser" the only service method I can use? I would prefer to be able to use my custom one.

EDIT:
code below works fine when I'm logged in as an admin user, otherwise it redirects me to login form, after form submission. Have I missed something in here?

public function actionAddPartner()
{
        $content = craft()->request->getPost();
        $companyId = explode("@", $content['email']);
        $user = new UserModel();
        $user->username         = $content['email'];
        $user->email            = $content['email'];
        $user->unverifiedEmail  = $content['email'];
        $user->firstName        = $content['firstName'];
        $user->lastName         = $content['lastName'];
        $user->pending          = true;
        $success = craft()->users->saveUser($user);
        if ($success) {
            // Assign them to the Partner Admin user group
            craft()->userGroups->assignUserToGroups($user->id, 1);
            // Update the Element Index
            craft()->search->indexElementAttributes($user);
        }
}


texts:
I'm using the Guest Entries plugin and it's all working great, the problem is I'm getting spammed like mad. I've got snaptcha installed which seems to be catching some of it but I could do with an IP log so I can see if it is coming from a certain IP or IP range.

I ideally want the IP logged with the form submission as server access logs are hard to match up.


texts: Avoiding includeJsFile, includeJS from caching

texts:
In my template, I have an includeJSFile that loads properly on the first load, but disappears on subsequent loads.

The includeJSFile is outside the caching tags, so I'm not sure why this is still happening. There's no caching in my layout.twig as well.

I also have a variable set in my template that I'm calling in via the includeJS tag (placed outside of the cache tags), and that seems to be having the same issue as well. Any idea to resolve this? Here's the setup.

{% extends "_layout" %}
{% block content %}
    {% cache globally using key craft.request.path %}

    {% set entries = craft.entries({
        section: 'MY-SECTION',
        with: [
        'MY-ASSET-FIELD'
        ]
    }) %}

    -- MY ENTRY LOOP --

{% endcache %}

{% includeJsFile 'MY-JS.js' %}

{% set MY-JS-VARIABLE %}

    -- MY JS CONTENT THAT LOOPS THROUGH SECTION ENTRIES TO INSTANTIATE MY JS OBJECTS --

{% endset %}

{% includeJs MY-JS-CONTENT %}
{% endblock %}


texts: Can I set shipping rates based on order value?

texts:
I'm trying to set up shipping rates the client used prior to Craft Commerce. So for example, if the cart total dollar amount is:

0.01-$35.00 rate = $21
35.01- $170 rate = $39
170.01-$275 rate = $44, etc.

is this currently doable or will the client have to switch to a per item or weight-based shipping cost?


texts: Can a redactor field be configured to save images in different folders?

texts: Can the same redactor field save inline images in a dynamically determined folder structure? Can something like asset field's upload location be configured for it?


texts: How can I filter Craft Commerce products by price

texts:
I'm trying to use price as a parameter for filtering my Craft Commerce products, but I cannot get it to work. I think the problem is with the way that I'm referring to the product price, but at the same time I'm not sure how to change it so that it will work.

Is it possible to filter by product price as I'm trying to do here ?
Does anyone know what exactly I need to change to get my query to work ?

Any pointers in the right direction would be most appreciated.

{% set queryParams = {
    relatedTo: category,
      price: [
       'and',
       '>= ' ~ 200,
       '<= ' ~ 500,
      ]
 } %}

{% set products = craft.commerce.products(queryParams) %}

{% for product in products %}
    ....output product data
{% endfor %}


texts: What is the difference between calling .first and .first()?

texts:
So here's something I've never been able to figure out about Twig. Does it make a difference if you include the parenthesis for functions or not?

In other words, what is the difference – if any – between calling

craft.entries.first

and

craft.entries.first()

?


texts: Is there an easy way to enable devMode only to users logged in with specific permissions?


texts:
I'm attempting to get matrix fields to populate in an entry form (using the guest post plugin) and so far just can't seem to crack it. I've tried various examples, but all assume that you're just editing an existing entry, not posting a new one (that a non-cp user would never need to edit).

The code is so wrong there's little point posting it.

I'm sure if someone can point me in the right direction, I'd be able to take it from there.

The matrix field is called traveller, the block is called travellerDetails and the field I want to try is called travellerTitle (a dropdown field).


texts: Sorting Entry Query Related By Custom Field

texts:
I am currently trying to speed up a website I work on, and would like to implement pagination as an index page is currently loading over 350 entries.

Each entry has a relation to another which holds data which is shared between different groups of entries.

On this website this takes the form of a store of yachts which holds all the data about them, from the price to the length and their images, these entries are then linked to from other entries for pages where that information is needed to be displayed, for example a yacht might be linked to from a sales page, or a charter page.

Within these parent entries for example charter there is an index page which displays all the yachts and is filterable.

The first query shown here shown how we are filtering the yachts down, this query will specifically query the underlying yacht data and return the ID's of all the yachts which match: https://pastebin.com/kK4gsWM4

The second query shown here takes the ID's of the yachts found above and finds the parent entries which are related of the correct type in this case charter: https://pastebin.com/TkyV6fxy

The issue is that I cannot sort the parent entries by the information contained within the yachts, for example I would like to sort by the length or price of the yacht.

To get round this I am currently using https://github.com/TopShelfCraft/SuperSort to sort the results after they have been returned.

This means however I cannot paginate the results as the sorting is done after the results have been returned.

So my question is, is there a way to order the parent entries by the values contained within the shared yacht entries?

I would greatly appreciate any help.

Thanks!


texts:
I want to output a list of all orders of all customers, including customers first name and last name. But can't get these two elements.

What I have now is:

{% set pastOrders = craft.commerce.orders.find() %}
{% for order in pastOrders %}
    {% for item in order.lineItems %}

      {{ order.id }}
      {{ craft.commerce.customer.firstName }}
      {{ craft.commerce.customer.lastName }}
      {{ item.description }}
      {{ order.email }}
      {{ item.options.evenement }}
      {{ item.note }}
      {{order.orderStatus.name}}
      {{ order.datePaid.localeDate() }}

    {% endfor %}
  {% endfor %}

But as you may guess, I've got an error in both fields firstName lastName


texts:
I'm trying to get all elements whose custom field satisfies a specific value. I've got the ElementCriteriaModel but I'm unsure how to set the field and value I'm looking for, from the documentation

$criteria = craft()->elements->getCriteria(ElementType::Entry);

Any ideas? If I'm not using the correct service, then which is the recommended one?

Thanks in advance

Update

Field in question is a datetime field by the name startTime. I'm searching for all entries whose date-part matches a given date


texts:
Is there any reason why min/max value are limited to the following?

[9999999999999]
- Min is too big (maximum is 2147483647)

I need to add ISBN numbers which are 13-digits. Is there a reason for this min/max length, and can it be increased?