texts: Best practice for multi site development, staging, etc. [Special snowflake details inside]

texts:
The story:

Site A is running in Craft 3 as the primary site. (On a subdomain, if that matters.)
Sites B and C are running in ExpressionEngine 2.
I need to write new HTML/CSS for sites B & C.
I need to import and cut/paste content from sites B & C so that eventually, sites A, B & C are all running under the original Site A Craft install.

Meanwhile, content will continue to be updated on Site A.

So...

If I clone Site A and develop with it, on my local PC, importing content from the other two sites, I can get all three sites running together. However, then I'm unsure how to reconcile the data from Site A with my development version.

What do folks recommend?


texts:
I'm trying to order the results of an entries query by the difference between two date fields but I can't seem to get it to work.
Here is my query:
{% set todaysStreamsParams = {
  section : 'films',
  orderBy : "DATEDIFF(`screeningDateFirst`, `screeningDateLast`) DESC",
  limit   : 5,
} %}

{% set todaysStreams = craft.entries(todaysStreamsParams).all() %}

But I'm getting the following database exception:
Unknown column 'screeningDateFirst' in 'order clause.

Any tips?


texts: How do you use the Element API plugin to output Assets from Matrix block for an entry?

texts:
I have Single Section(entry) with Matrix field which contains Assets in blocks. I'm trying to fetch assets from a single Matrix block.

My element-api.php code is:

<?php

use craft\elements\Entry;
use craft\elements\MatrixBlock;
use craft\elements\Asset;
use craft\helpers\UrlHelper;

return [
  'endpoints' => [
    'api/portfolio/<blockId:\d+>.json' => function($blockId) {
      return [
        'elementType' => MatrixBlock::class,
        'criteria' => ['ownerId' => '4351', 'fieldId' => '218', 'id' => $blockId],
        'pretty' => true,
      ];
    },
  ]
];

Part of output is:

   "join": [
            [
                "INNER JOIN",
                "{{%relations}} relations",
                [
                    "and",
                    "[[relations.targetId]] = [[elements.id]]",
                    {
                        "relations.sourceId": "4402",
                        "relations.fieldId": "219"
                    },
                    [
                        "or",
                        {
                            "relations.sourceSiteId": null
                        },
                        {
                            "relations.sourceSiteId": "1"
                        }
                    ]
                ]
            ]
        ],

so it looks like I'm trying to access related field id 219 which is Assets field inside Matrix block.

Fields structure:

Any ideas?


texts:
Im trying to update an entry field programatically. I can load an entry by any field with a function i created

    /**
 * Returns an element by any attribute.
 *
 * @param int $elementId
 * @param string|null $type
 * @param string|null $localeId
 * @param string $localeId
 * @return BaseElementModel|null
 */
public function getElementByField($elementId, $elementType = null, $localeId = null, $field)
{
    if (!$elementId)
    {
        return null;
    }

    if (!$elementType)
    {
        $elementType = craft()->elements->getElementTypeById($elementId);

        if (!$elementType)
        {
            return null;
        }
    }

    $criteria = craft()->elements->getCriteria($elementType);
    $criteria->$field = $elementId;
    $criteria->locale = $localeId;
    $criteria->status = null;
    $criteria->localeEnabled = null;
    return $criteria->first();
}

but i cant save the new values of the fields i want.
This is my save code:

$entry = $this->getElementByField("3081001100390", ElementType::Entry, null, "variantSku");
    $entry->variantSku = 1;
    craft()->entries->saveEntry($entry);

And the error is  Property "Craft\EntryModel.variantSku" is not defined. I know the variantSku exists since im loading a product by that attribute and i can see it when dumping $entry->variantSku.

Complete error here: https://www.diigo.com/item/image/4u33k/972k

Did anyone achieved this?


texts: Can't save entries with dynamic subfolder path in Matrix

texts:
I have a Matrix field which contains several assets fields. Each has the dynamic subfolder path set to {owner.section.handle}, so I can reuse the Matrix in multiple sections, but keep the assets organized.
When I try to save an entry with an image, i get the error:

Craft\InvalidSubpathException
Could not resolve the subpath “{owner.section.handle}”


texts: How to save data from a form in Craft? Explain with an example?

texts:
where do you handle the POST requests?
where do you write the validation rules and flash error messages?
where do you write save to db code?
(mainly i want to know how do you route a POST request to a controller and where do you write the controller?)


texts:
How do I mark a cart as complete from a plugin?
I tried setting isComplete = 1, it gets moved to orders but it is still a cart.


texts: Is it possible to extend the lifetime of the CraftSessionId cookie?

texts:
I would like to extend the lifetime of the CraftSessionId cookie. Is this possible and if so, where can I change the value?

Thank you for your time.


texts: Group entries by section, then order and combine sections

texts:
I'm grouping search results by section, based on Aaron Berkowitz's answer to this question. My code looks like this:

{% set entries = craft.entries({search: {query: keywords} }) %}
{% set entriesBySection = entries | group('section') %}

{% for section, entries in entriesBySection %}

{{ section }}

        {% for entry in entries %}

{{ entry.title }}

        {% endfor %}

{% endfor %}

That works great but I need to show the sections in a specific order, and merge some sections into one. So I'd end up with, for example:

News
Products
Reports
Other (everything else combined)

Any idea how to do this?

Thanks loads for any help!


texts:
I have a structure section with entry url format: "products/{slug}".
All entries have they urls like "/products/category1/subcategory1/product1".

Currently, I have a header navigation which opens product category pages like "products/category1".What is the preferred way to define "/product" page?


texts: Can I call a dynamically named variable through twig?

texts:
I am using Craft 3 with the Commerce 2 plugin.

I am trying to dynamically call a variable in a twig template where this variable has to be a "placeholder" for a handle of a field inside a block inside a matrix field.

Here is an example snippet which visualises my problem:

{# 'product' variable is passed to this template #}

{% set fields = product.productFields %}
{% set categoryOptions = [] %}
{% for cats in fields.type('categories') %}
    {% for category in categories.fieldLayout.fields %}
        {% set categoryOptions = categoryOptions|merge([category.name]) %}
    {% endfor %}
{% endfor%}

{% set productId = product.id %}
{% for catOption in categoryOptions %}
    {# Here is where I try to call catOption as a 'placeholder' #}
    {% set productId = productId~ '-'~ categories.(#{catOption}).label %}
{# I have also tried using:
{catOption},
catOption,
#{catOption} etc but nothing seems to work #}
{% endfor %}

Usually I could call the 'categories' one by one but I want everything to be dynamically set.

I know that in some languages you can call a function/property like that or assign a variable with such value.

Any suggestion for a solution or a workaround would be useful. Thank you in advance!


texts: Allow Author to Build Multiple Choice Question?

texts:
I'd like to allow authors to add a multiple choice question to an entry.

To build the possible answers, they will create answers and mark one as the correct answer. I could then output these as radio boxes on the frontend and allow website users to choose one and get 'marked'.

Since there is only a single question (with multiple answers) per entry, I'd like to avoid using a form plugin (such as Sprout Forms, which may be able to support this).

Anything I've tried did not have the ability to mark one and only one answer as Correct. I first built a table with 'Answer' (plain text) and 'Correct?' (lightswitch) fields in each row; this allowed choosing multiple answers as Correct. I then turned it into a SuperTable and made the 'Correct?' field radio buttons...but could not get all the rows in the table to be a single set of radio buttons such that you could only choose one.

Any ideas? Creative ways of building this differently are welcome. Thanks in advance.


texts: Do I need a plugin to load entries via AJAX?

texts:
I want to load some entries via AJAX. I have a page that normally shows all entries of a specific type with user-selectable filters. I want to load filtered entries via AJAX.

Do I need to create a plugin to do this? If so, how can I use the Craft object in my JavaScript code to call Craft.ajaxActionRequest or Craft.postActionRequest?


texts: How do I resolve dependency conflicts in Composer?

texts:
I'm new to using Composer and I'm having trouble deploying to Laravel Forge. I am getting an error message that says:

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

  Problem 1
      - Installation request for illuminate/support v5.5.44 -> satisfiable by illuminate/support[v5.5.44].
      - don't install tightenco/collect v5.5.33|don't install illuminate/support v5.5.44
      - Installation request for tightenco/collect v5.5.33 -> satisfiable by tightenco/collect[v5.5.33].

I didn't add these packages, they are dependencies of something I have added. So I have a few questions:

First, how do I resolve this? I am thinking that I should not go in and try to change the version numbers on anything because that would break things most likely, correct? Also, since they are not in my composer.json file, I'm not sure how I would do this.

Second, how do I determine what package I am installing uses this as a dependency?

Third, I have a couple of plugins that I have uninstalled in the CP that are still showing up in the composer.json file.Do I need to go back into my composer.json file and remove them? I thought this was done automatically when a plugin was uninstalled, but that may be my mistake. I am wondering if one or more of those plugins might be the culprit.

Thanks,

Brian


texts: How do I have my control panel in English but my site locale to Dutch?

texts: I prefer my cp in English but I've noticed that it also sets the locale to "en_us" for the entire site. I need that locale to be "nl" since the site is in Dutch. Any idea how to achieve this?


texts:
I'm currently creating some standard templates which should help to find good defaults for matrix output. This is where I stumpled upon the somehow weird structure of table data.

Here's a simplified structure of what I want to build:

{% for row in table %}

  {% for data in row %}
    {{ data }}
  {% endfor %}

{% endfor %}

Outputting table content like this:

{% for row in table %}
  {{ dump(row) }}
{% endfor %}

shows me that each row has double entries:

array(6) {
  ["col1"]=> string(7) "Hamburg"
  ["col2"]=> string(7) "1730000"
  ["col3"]=> string(7) "2600000"

  ["city"]=> string(7) "Hamburg"
  ["population"]=> string(7) "1730000"
  ["urbanPopulation"]=> string(7) "2600000"
}

While this might make sense in some cases, I don't get it. Why is this behavior and in which cases could the convention "col1", "col2", etc. make sense?

On first sight, this choice is very unfortunate as it prevents dynamic table output. Sure, you could use hacks like loop.index to target these, but that makes the code very unreadable and ugly.

Does anyone have the same issue with this?


texts:
I am trying to get my head around the TaskService that Craft comes with. I want to create a task that periodically (say every 15 minutes) uses the Twitter API. I am currently creating a task modeled on Pixel & Tonic's PowerNap which was very helpful, but I still don't understand how the tasks are triggered.

In the createTask method I didn't see any duration or anything like that and if the tasks are created within a controller that would have to be posted to, would this require a tandom cron job to trigger it from the server?

Any clarifications, insights, or references that might be helpful in better understanding the TaskService would be greatly appreciated as the Class Reference's docs aren't really that helpful.

Thanks!


texts:
I have a group website which has a main site and 3 sub sites all within 1 Craft Installation.
Each sub site has its own Structure Section for Content.

I am adding a Group Wide Search to the main site and sub sites.
Sub sites are accessed by subdomain of main site - e.g.  property.domain.com agents.domain.com

On a sitewide search if I get results from the subsites the entry.url will just contain the domain from the site it is being searched for.

So for my search results - I will check the handle of the entry to see if it is from the subsites - and then if possible replace the domain.

I can get the handle with:

{% set handle = entry.section.handle %}

Is there a handy way to replace the domain?


texts: Where to find info on Entry URL Formats and routing syntax/options?

texts:
Is there any documentation other than on the CraftCMS web site with details and examples of Entry URL Format options/syntax? I came across an example from Brandon Kelly in this thread yesterday which gave me much insight and a solution to an entry url issue of my own, and I'd like to learn more about this as well as Routing options.

Tips appreciated.


texts: How to get previous and next entry using the native GraphQL API?

texts:
How do I turn these Craft queries into a GraphQL one?

// entry.twig

entry.getPrev({ section: "contentHub" })
entry.getNext({ section: "contentHub" })

I want to get the previous and next entry using the current entry


texts:
I have a search results page set up where there are a number of parameters in the query string used to filter results. I've got 3 out of 5 of these working and am stuck on the final 2.

My full template is below with the two parameters that are nto working correctly marked with NOT WORKING.

  {% set params = {
    section: 'books',
    limit: 12,
    orderBy: 'authorLastName'
  } %}

  {# text query working #}
  {# set search values from query string #}
  {% set searchQueryKeywords = craft.app.request.getParam('q') %}
  {% if searchQueryKeywords !="" %}
    {% set params = params | merge({
      search:'title:' ~ searchQueryKeywords ~ ' OR bookAuthors' ~ searchQueryKeywords, })
    %}
  {% endif %}

  {#
  // NOT WORKING
  // get related country
  #}
  {% set countrySlug = craft.app.request.getParam('country') ?? null %}
  {% if countrySlug != null %}
    {% set searchQueryCountry = craft.categories.group('country').slug(countrySlug).one() %}
  {% endif %}
  {% if countrySlug is defined and searchQueryCountry is defined %}
    {% set params = params | merge ({
      relatedTo: [
        'and',
        { targetElement: searchQueryCountry }
      ]
    }) %}
  {% endif %}

  {#
  // NOT WORKING
  // if age is not null then merge related to age #}
  {# get related age rating #}
  {% set ageSlug = craft.app.request.getParam('age') ?? null %}
  {% if ageSlug != null %}
    {% set searchQueryAge = craft.categories.group('recommendedAges').slug(ageSlug).one() %}
  {% endif %}
  {% if ageSlug is defined and searchQueryAge is defined %}
    {% set params = params | merge ({
      relatedTo: [
        'and',
        { targetElement: searchQueryAge }
      ]
    }) %}
  {% endif %}
  {# end age #}

  {# working if authors is not null then merge related to authors #}
  {# get related author #}
  {% set authorSlug = craft.app.request.getParam('author') ?? null %}
  {% if authorSlug != null %}
    {% set searchQueryAuthor = craft.entries.section('authors').slug(authorSlug).one() %}
  {% endif %}
  {% if authorSlug is defined and searchQueryAuthor is defined %}
    {% set params = params | merge ({
      relatedTo: [
        'and',
        { targetElement: searchQueryAuthor }
      ]
    }) %}
  {% endif %}
  {# end authors #}

  {# working language #}
  {# this is a checkbox field #}
  {% set searchQueryLanguage = craft.app.request.getParam('language') ?? "null" %}
  {% set languageSearch = 'bookLanguages:' ~ searchQueryLanguage %}
  {% if searchQueryLanguage !="null" %}
    {% set params = params | merge({ search: languageSearch }) %}
  {% endif %}

  {# set the entries with all the search/fitering params #}
  {% set entries = craft.entries(params) %}
  {% paginate entries as pageInfo, pageEntries %}

  {% for entry in pageEntries %}

{{ entry.title }}

  {% endfor %}

I cannot figure out why country and age are not working. I even manually created a test div with the relationships from the query string and this section outputs results as expected. However I can't get it to work within my main search results area.

Here is my testing div:

    manually relate entries (limit 2) to age of query string parameter

  {% set age = craft.categories.group('recommendedAges').slug(ageSlug).one() %}
  {% for test in craft.entries.section('books').relatedTo(age).limit('2').all() %}
    {{ test.title }}

  {% endfor %}

    manually relate entries (limit 2) to country of query string parameter

  {% set countryName = craft.categories.group('country').slug(countrySlug).one() %}
  {% for test in craft.entries.section('books').relatedTo(countryName).limit('2').all() %}
    {{ test.title }}

  {% endfor %}


texts:
I've been stumped on this one for awhile and tried everything. When I click Clear Caches in settings, it appears as if everything works fine but when I check the logs I see...

2015/11/04 17:10:16 [error] [application] Tried to read the folder contents of path/cms/craft/storage/runtime/cache/, but could not.
2015/11/04 17:10:16 [error] [application] Tried to read the folder contents of path/cms/craft/storage/runtime/assets/, but could not.
2015/11/04 17:10:16 [error] [application] Tried to read the folder contents of path/cms/craft/storage/runtime/temp/, but could not.

I ommited the actual path because it contained a clients name but I checked it's accuracy. I also noticed that it appears to be writing files to the cache folder. I also verified permissions on the folders and parent folder, all are set at 777 (for testing) was set at 744. I'm not sure what else to try or do. Thanks!


texts: Initialisation, failed to determine IP address

texts:
Thought I'd give Nitro a whirl but can't get past initialisation.
Initialize the primary machine now? [yes]
How many CPU cores? [2]
How much memory? [4G]
How much disk space? [40G]
Which version of PHP? [7.4]
Which database engine? [mysql]
Which version of mysql? [5.7]
Applying the changes now...
launch failed: The following errors occurred:
failed to determine IP address
Error: exit status 2
ianebden@Ians-MacBook-Pro ~ %

Anyone else encountered this? Any advice much appreciated.


texts: Javascript events when modal window is opened or closed

texts:
How can I detect when a modal window has been opened or closed?

I am writing a plugin which wants to detect when a garnish elementeditor modal window has been opened or closed.


texts: Craft 2 FormBuilder 2 equivalent plugin in Craft 3

texts: Is there any plugin equivalent to Craft 2 FormBuilder 2 plugin in Craft 3? My Craft 2 website forms are built with FormBuilder 2. I upgraded the website to Craft 3, but FormBuilder 2 is not working. I need an equivalent plugin to work in Craft 3.


texts: GraphQL returning array on entries field with limit set to 1, instead of 1 object/entry

texts:
If I do a GraphQL query on an asset (entries field type, limit set to 1), I get an array in return. Even if I limited the asset to just 1 in the field. So my GraphQL returns:
"image": [
  { "alt": "some alt text", "src": "http://the-image.jpg" }
]

With GraphQL:
image {
  alt: title
  src: url
}

Now is it possible to return just the first object in GraphQL one way or another? If not, what function should I look into when I copy/past the existing assets field type into my own custom field type returning just the first value of the array? I couldn't find it when looking into the field types, so must be some magic method I am guessing (or not possible at all)?


texts: Calling Craft Console Commands from Plugin?

texts:
I am in the process of building a plugin that has a controller that accepts a HTTP request. If the token and request are valid, I would like to call a Craft Console Command from within the plugin (e.g. gc/run or resave/entries).

The equivalent would be using the CLI for call the command ./craft gc/run but from a controller.

How would I call the command from my plugins HTTP controller?


texts: What's the difference between a Component and a Model in Craft 3?

texts: I'm trying to familiarize myself with the Craft architecture and I can't understand whether I should be extending craft\base\Component or craft\base\Model for my business logic models. Component seems like a pretty lean class that only adds a few initialization events to Model.


texts: Use different template for same route based on user group

texts:
I'd like to have consistent URL's for an account section but depending on the current users group, the template will be different. I know I could use the same template but there would be a lot of if/else's throughout and I'd like to avoid that.

URL pattern would be something like this:

If customer group
'account/settings' => '_dashboard/customer/settings'

If admin group
'account/settings' => '_dashboard/admin/settings'

I was thinking this might be possible with a plugin controller that each route would hit and then decide which template to render.

For both groups
'account/settings' => ['action' => 'action/path']

function action()
{
   // Get user
   // Set path based on user group
   // Set template path to front end
   // Render template
}

Can you see any problems with the above solution? Will there be much of a performance hit? Is there a better way?


texts: Show/display entries next/prev except entries with lightswitch field active

texts:
I have projects on my portfolio that link to each other. I'm currently using previous and next links.

This is what my code looks like

{# Set parameters for prev/next elements list #}
{% set params = craft.entries.section('portfolio') %}
{# Get the prev/next elements #}
{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}

And then I call it to display it in my code like so:

    {% if prevEntry %}

            Previous
            {{ prevEntry.client }}

    {% endif %}
    {% if nextEntry %}

            Next Project
            {{ nextEntry.client }}

    {% endif %}

My goal today is to hide the previous entry button if the previous entry has the comingSoon lightswitch field ON.


texts: Where to store asset backups for plugin?

texts:
I need to store revisions of assets for a plugin I am working on, what is the best / most robust location to store them?

I need the location / files to:

Always be writable.
Not removed when / if craft/storage is cleaned out.
Unaffected by updates or cache being cleared.

S


texts: getting fields of a section (getFields())

texts:
I feel like I'm doing this wrong (looping on section fields):

{% for fieldLayoutField in craft.entries.section('rentalsBulletin').getEntryTypes().first.getFieldLayout().getFields() %}
    {% set field = craft.fields.getFieldById(fieldLayoutField.fieldId) %}
    {% include 'rentals-bulletin/_components/form-field-types/' ~ field.type %}
{% endfor %}

Building a front-end "create" page. Goal is loop through fields and depending on type include a snippet to build the form. Basically, get section fields and build the form dynamically.

EDIT: if you didn't see the accepted answer comments, the way to do this when you don't have an entry to work with is:

{% for fieldLayoutField in craft.sections.getSectionByHandle('rentalsBulletin').getEntryTypes()[0].getFieldLayout().getFields() %}


texts: Display Matrix block field base on location of query

texts:
supportContent is a Matrix field
contentBlock is a Matrix block
heading and body are fields within contentBlock

I am trying to display block.heading only if my query is in the block.body

{% for block in entry.supportContent.type('contentBlock') if query in block.body  %}
    <h3>{{ block.heading }}</h3>
{% endfor %}

This code is not working. Any help?


texts:
I am writing a console plugin to import a load of gallery images from an old site into a new craft site. I need to create folders in the assets area, import the images, then create custom entries to represent the galleries.

I am hitting a hurdle at the first task, creating a folder. It fails with a general message like "Error creating folder". I assume it's because I am not "logged in" and therefore have no permission to create the assets folder.

So I tried to do a craft()->userSession->loginByUserId(1) but I got the complaint about no ip address or user agent string. I checked the code and saw that there is a config item to turn this check off, but the method loginByUserId() doesn't use it.

Is there a way to force a login from a console plugin so that I can do privileged operations?


texts: ServiceUnavailableHttpException on front end, and 404 on admin

texts:
Trying to get started with Craft CMS 3 for the first time, and it's running locally via Valet. from the front end, I get:

> HTTP 503 – Service Unavailable – craft\web\ServiceUnavailableHttpException

And on the admin side, I'm getting a 404. I've looked at similar questions, but none of the answers are helping me. I've set this up twice following this article on running Craft with Valet, and gotten the same result both times.


texts: Why is it when I update an entry within a structure in the admin, it reorders it to the bottom of the list?

texts:
I've created a structure and I have about 15 entries in it. They are grouped under an entry named "0234" and each entry below it is named 0234 A, 0234 B, 0234 C, etc. I would like to keep them in this order but if I edit 0234 B and save it, it re-orders it to the bottom.
Is this normal behaviour or am I missing a configuration option somewhere?


texts: how to output all images in an entry's loop

texts:
Unfortunately I'm still very new to Craft, but I have a question to which I haven't found an answer here or in the Docs or the ones I found don't seem to work in my case.

I want to output all the images for each entry in this loop and I don't understand how I get the "set image = entry.startbilder" to work that way?

I understand that ".one()" only outputs the first image but how do I change that to output all images? changing that to ".all()" results in an error.

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

        {% set image = entry.startbilder.one() %}
        {% if image %}

        {% endif %}

{% endfor %}

thanks in advance for any help!


texts:
I have imported data with 18000+ entries. It's a list of product models with brands associated to each. The product model is being used as the title and the brand field is plain text.

There are approximately 140 brands which I need to output as a dropdown.

I can't output this many entries and then try and group (and order them) on the template as it crashes the page.

This is code that would work if it didn't crash the page (and would take minutes to load the page even if it didn't).

{% set allEntries = craft.entries.section('solarWaterHeaterModels').order('brand asc').limit(null).find() %}

{% set allEntriesByBrand = allEntries|group('brand') %}

{% for brand, entriesInBrand in allEntriesByBrand %}

    {% for entry in entriesInBrand %}
        {% if loop.index == 1 %}
            <option value="{{ entry.brand }}">{{ entry.brand }}</option>
        {% endif %}
    {% endfor %}

{% endfor %}

Can anyone offer some guidance on how to approach this please?

Many thanks


texts: Is it possible to use same template for index and archive template?

texts:
I'm new to Craft from ExpressionEngine and wondered how people handle Month/Year archive pages.  I have figured out how to get the archives to display but the code seems overly complex.  I wondered if there is a more straightforward approach or if it is possible to display your archive using the same template as the news/index  which displays all. In EE this was possible and just wondered if it was in Craft.

Thanks in advance.  My archive template code below.

{% if month is not defined %}
    {% set before = year + 1 %}
    {% set after  = year %}
{% else %}
    {% if month == 12 %}
        {% set yearBefore = year + 1 %}
        {% set monthBefore = '01' %}

        {% set before = yearBefore~'-'~monthBefore %}
        {% set after = year~'-'~month %}
    {% else %}
        {% set before = year ~ '-' ~ (month + 1) %}
        {% set after  = year ~ '-' ~ month %}
    {% endif %}
{% endif %}

{% set allEntries = craft.entries.section('news').limit(null).after(after).before(before) %}

{% for date, entries in allEntries | group("postDate|date('F Y')") %}

Entries from {{ date }}

    {% for entry in entries %}

            {% for asset in entry.newsthumb %}

            {% endfor %}

{{ entry.title }}

                <time datetime="2017-07-27" class="post-time">{{ entry.postDate.format('F d, Y') }} </time>

                {{ entry.newssummary }}

                {% if entry.newscategory | length %}
{% endif %}
                {% nav category in entry.newscategory %}

{{ category.title }}{{ not loop.last ? ', ' }}

                {% endnav %}

                {% if entry.newscategory | length %}
{% endif %}

    {% endfor %}
{% endfor %}


texts:
I've currently setup a matrix-field for adresses. I added the field as required field to my user-group "Customer". Which breaks the registration, as a user can only be registered, when the matrix has at last one entry.

What im missing now is the possibility to add the specific input elements for one single address-block (or matrix entry) so the user has to add at last one address at registration.

When logged in and viewing the profile, the user should also be able to manage  his matrix entries, so managing multiple addresses.

Is there any documentation on how to get the backend-matrix-editor into the frontend? Can anyone link me an example without copying the whole backend stuff into the frontend?


texts: Filter entries by matching an url segment to Checkboxes Field values

texts:
I have succsefully managed to filter entries by matching an url segment to a Radio Buttons Field in my entries, like this:
(here category is the field handle of my Radio Buttons field)

{% set filteredEntries = craft.entries.section('news').category(craft.request.getSegment(2)) %}

After having to change the Radio Buttons Field to a Checkboxes Field I tried adapting my code like this:
(here category is the field handle of my Checkboxes Field)

{% set filteredEntries = craft.entries.section('news').category.contains(craft.request.getSegment(2)) %}

But it doesn't work. Any suggestions?


texts: Validation not running on empty custom fields on an entry (when creating programmatically)

texts:
I'm trying to save an entry via a controller. They are contact form submission. A few of the fields are required.
    $section = Craft::$app->sections->getSectionByHandle('contactSubmissions');

    $entry = new Entry();
    $entry->sectionId = $section->id;
    $entry->typeId = 2;
    $entry->authorId = 1;
    $entry->enabled = true;

    $entry->setFieldValues([
        'contactName' => ucwords($data['contactName']),
        'contactEmail' => $data['contactEmail'],
        'contactCompany' => $data['contactCompany'],
        'contactMessage' => $data['contactMessage'],
        'contactHeardAbout' => $data['contactHeardAbout'],
        'contactWebsite' => $data['contactWebsite'],
        'contactTitle' => $data['contactTitle'],
    ]);

    if ( Craft::$app->elements->saveElement($entry) ) {
        //$this->sendMail($entry);
    }

    die(var_dump($entry->getErrors()));

    return $entry;

The only validation that runs if the missing title, which in this case is the contactName. All other keys in the $data array are empty strings. They do not trigger any validation and the empty entry saves into the database.
If I were to go into the control panel and try to save the entry, it would fail with the validation errors.
If I were to enter a value for the email field, but have an invalid email, that validation then gets triggered. But none of the empty fields do.

Additional info
Craft version: 3.6.10
PHP version: 7.3.13


texts: Customizing the destination after user activates the account

texts:
I would like to ask about activation e-mail which is sent to new user.

Once the user clicks the link, it redirects to homepage.
Is it possible to change the destination?
I would rather like to make it to login page.


texts:
I have a field call "scripts" to house scripts like a marketo form script. This gets added in an entry template, but I need to pass this to the layout (if there is something in the field) and render in the footer.

Is this possible? I'm open to ideas or suggestions.


texts: How to check structure type has any entries/children from anywhere on my site?

texts:
I have a section with a "Structure" section type. I've called it "structure_casestudies".

I'd like to create a navigation bar that links to that page, but only if there is at least one entry within it.

hasDescendants() or similar EntryModel functions work fine, for structure pages only. But how can I perform the same check, from anywhere on the site?

I hoped doing a specific query would do the trick... but this just isn't right.

{% if craft.entries.section('structure_casestudies').hasDescendants() %}Case Studies{% endif %}

Any ideas?


texts: How can I get/check the contents of a cart via javascript (cookie)?

texts:
Within my application, I would like to only show a link to the the user's cart only if there are products in it.

I was going to use javascript to check the cookie I can see getting set. commerce_cookie

The problem I'm having is how to read that cookie. I realize its encrypted & I'm not accessing the cookie correctly. That's why I'm unable to get and check for any orders. Is there a better way to check the cart dynamically in this way?

I am trying to read it like this:

var cart = getCookie('commerce_cookie');

console.log(cart);  // false

// check if there are any products in the cart
if (cart) {
   // show the cart icon
} else {
    // hide the cart icon
}

function getCookie(cookie) {
    if ($.cookie(name)) {
        returnJSON.parse($.cookie(name));
    }
}

I have read through this thread about LJ Cookies, but I'm still not confident I'm looking for the cookie correctly:

{{ craft.lj_cookies.get( 'commerce_cookie' ) }}

SOLUTION

What I was tying to do was hide the cart icon and only show it (along with item quantity) only if there were items in the cart.

To do this, you'll need a plugin to listen for the onBeforeAddToCart event.

MyPlugin.php

// Listen for items getting added to the cart.
craft()->on('commerce_cart.onBeforeAddToCart', function (Event $event) {
    $cart = craft()->commerce_cart->getCart();
    // set expire & other params as needed
    $cookie = new HttpCookie('totalQty', $cart->totalQty);
    craft()->request->getCookies()->add($cookie->name, $cookie);
});

Then I've got an ajax request that will check if that cookie exists.

jquery

var data = {
    'CSRF': $('input[name="CSRF"]').val()
};

$.ajax({
    'type': 'post',
    'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
    'cache': false,
    'data': data,
    'url': '/actions/myplugin/checkCookie',
    'dataType': 'json',
    'timeout': 50000
}).done(function (response) {
    // handle response
}).fail(function (error) {
   // Total fail.
});

That routes to a controller method within my plugin:

MyPlugin.php

if (craft()->request->isAjaxRequest()) {
    return $this->returnJson(craft()->request->getCookie('totalQty'));
}

Here is how I am then handling/updating the UI with the results of that ajax request. I am summarizing my code here, there is more logic than I am listing - just trying to keep the size of this thread below the level of "book".

I am using velocity for my transitions.

jquery

 ...
 var qty = (result.value + 1);  // value is zero-based array so +1

  $('#icon').velocity('fadeIn', {
      'duration': 300,
      'display': 'inline-block',
      'complete': function () {
          $('<div/>', {
              'id': 'cartQty',
              'text': qty
          }).appendTo($('#icon'))
              .velocity('transition.bounceIn', {
                  'duration': 300,
                  'easing': 'easeInOutSine'
              });
          }
      });

I wasn't able to find an event that listened for the Empty Cart event, so I had to get creative here.

I listen for the "Empty Cart" form submit via jQuery. From there I make another ajax request to my plugin:

jQuery

$('#emptyCartForm').submit(function (event) {
     deleteCookie(); // calls an ajax method (below)
});

$.ajax({
    'type': 'post',
    'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
    'cache': false,
    'data': data,
    'url': '/actions/myplugin/deleteCookie',
    'dataType': 'json',
    'timeout': 50000
}).done(function (response) {
    // handle response
}).fail(function (error) {
   // Total fail.
});

That request makes a call to a controller method within my plugin:

MyPlugin.php

 if (craft()->request->isAjaxRequest()) {
     craft()->request->deleteCookie('totalQty');
     return $this->returnJson(['status' => 'success']);
}

I'm happy to edit or please feel free to edit if there is any way I can improve this technique.


texts: Running Craft alongside another CMS on the same domain

texts:
I've started working with a marketing team for a well established online ecommerce store.

Their site is a custom ecommerce CMS build (handled by another third party), which works well technically, but the marketing team have regularly expressed how difficult it is for them to create visually interesting and engaging pages within the site, as it's geared so much towards ecommerce.

Currently the only options the marketing team have when adding new pages from the ecommerce CMS is a textarea (single column, bold, italic, links) and a single image.

Updating the ecommerce CMS to give the marketing team greater flexibility is currently not an option (due to history and internal politics). This then led to the conversation of running 2 CMS's on the same domain - 1 for handling the ecommerce and 1 for the blog and product specific promotional landing pages. I showed them Craft, and they loved it!

The Question(s)

First off, is running 2 CMS's on the same domain possible / advisable? (I remember hearing Joel Bradbury mention running EE and WP on the same domain at EEUK)

Are there any obvious pitfalls or gotchas?

I'm assuming it would be simple enough to have Craft handle any blogs if set up on a blog URL (eg: domain.com/blogs/blog-post-name).

But what about specific landing pages (eg: domain.com/discount or domain.com/freestuff)? In theory could I create a route from the ecommerce CMS to point to the Craft generated page? Or should all marketing pages live in the same directory (eg: domain.com/marketing/discount or domain.com/marketing/freestuff)?

Ideally I'd also like to be able to dynamically insert product data (prices, images, descriptions, etc) into the blog and landing pages created in Craft from the ecommerce site. I'm assuming hooking a Craft plugin up to the ecommerce API (if there is one) would be the best option to pull in the data? (Or would scraping be an option?) We would also need to mirror the ecommerce navigation on any Craft generated pages.

The end goal is to give the marking team the freedom and flexibility to add interesting and engaging promotion pages, and have them look native and integrated into the main site.

Apologies, I know there's a lot of questions here. And some non-Craft specific, but I'm hoping this is a good place to start my investigation.

Many thanks!


texts: Serializing assets field is returning a serialized criteria object, but how to return serialized data?

texts:
I'm saving a custom element that has content by field layout.
When successfully saved, I return the object in the response.
Now, most of the data is usable but the assets field is just a serialized criteria query.

return $this->asJson([
    'success' => true,
    'quotation' => $quotation
]);


texts: How to round the decimal value which we store in the admin panel?

texts: Is it possible to round the decimal value we store in the admin panel . Can anyone Explain me with an example


texts: How to load entries data in the General Configuration file?

texts:
I'm trying to set dynamic paths for values such as activateAccountSuccessPath.

This kind of code below from my routes.php file works very well:

use craft\elements\Entry;

$myAccount = Entry::find()->section('myAccount');

return [
    $myAccount->type('user')->one()->uri . '/<id>-<slug>' => ['template' => '_myAccount/user']
];

But it seems that craft\elements\Entry can't be used at the top of general.php (which make sense...).

Any idea of a simple workaround to load Entry data at this time? Like this, I could set dynamic paths depending of the context and language.

I know I could already set paths like this:

'activateAccountSuccessPath' => array(
     'fr' => 'mon-compte',
     'nl' => 'mijn-account'
),

But this is not enough, I would like the path match dynamically another existing URI in a Structure.


texts: Craft CLI ./craft - can I tell it to use a specific php version when running composer via the CLI?

texts:
With the Craft CLI, is there a way to set which php version to use?
The context here is that the server runs PHP 5.4 for another project, but PHP 7.3 is installed at /usr/bin/php73 and is setup in Apache to use that version for this specific site.
With normal composer install I just specify the path to that version like so:
/usr/bin/php73 /usr/bin/composer update
but I want to be able to run updates via the Craft CLI. The CLI tool then uses the composer version on the server. Is there a way to specify what version of php to use when running commands via the CLI?


texts:
I've got a number of assets directories set up. One of them is having an issue where if you upload an image it doesn't appear in the control panel despite having been uploaded to the server. I checked and it's in the directory.

When uploading you see the upload progress bar, then that disappears and the image doesn't appear anywhere.

Not sure how to resolve this. Please advise.


texts: Credit card fee to the final order in CP

texts:
I need to add the credit card fee to the order in the CP. I get a response from the gateway with a custom txnfee variable and would like to view it in the CP. Just like an custom adjuster. Does anyone have any experience with that?

Example:

Order = $100
Tax = $5
Credit card fee = $1
Total = $106


texts: Live Preview not showing content, Craft 3

texts:
I use the same templates for live preview as for the front end. Until a recent change in Craft 3, they worked fine for live preview, then they stopped showing most fields.

I use a lot of includes to build pages, for example, I send the id of an entry to a separate template to display a Matrix field. I just pass entry.id.


texts: Multiple category output in auto generated entry title

texts:
I have a single category field (named category) in my section and I am looking to use the auto-generated title to keep these entries titled consistently. I have had success outputting the first category selection into the entry field but I can't seem to grab multiple selections. I have tried a for loop and I can of course getting working on a template but I am thinking the syntax must be different for the auto generated title field.

Here is an example of the tree I am working with.

Category One

Sub Cat One
Sub Cat Two

In a example entry I will have Sub Cat One selected and of course Category One since it is an ancestor of the Sub Cat One. I would like to output something like (Category One / Sub Cat One) in the entry title but I either get no results or just the first one. I have tried the following code:

{% for categoryList in category %}{{categoryList.title}}{% if loop.index < loop.length %}/{% endif %}{% endfor %}

and

{category.first().title}

Which of course contains only the first selected category title.

How do you output more than one category selection in an entry title field?

Thanks!


texts: {% paginate %} Tag issue, no prevUrl / nextUrl Data

texts:
I have problem with the {% paginate%} tag.

Setting:

Craft CMS 3.0.18
Channel with 3 Entries -> handle "newsBlog"

{% paginate craft.entries.section('newsBlog') as pageInfo, pageEntries %}

When i open the second Entry in the News-Channel i get following values

pageInfo.total: 3
pageInfo.currentPage: 1 -> Why?
pageInfo.nextUrl: empty -> Why?
pageInfo.prevUrl: empty -> Why?

I did a lot of Craft 2 projects without pagination problems.

What did I do wrong? Thx for help!


texts: Craft Commerce: Export each order to a specific CSV file and send it throught email

texts:
Although I don't like this for some reasons, my client wants Craft Commerce to directly send specific formatted CSV file to their CRM system for each order.

Is it possible to write a Craft Commerce plugin to allow such a feature ?


texts: Use global values in the Entry URL Format field

texts:
I'm trying to use global variables in Entry URLs generated by Craft, but they seem to be empty. Not getting any errors as such, just null.

My Entry URL format looks like this:

{{siteDefaults.artworksList.first.uri|default}}/{slug}

Where artworkList is an entry with a URI/URL but I'm getting "/some-entry-slug"

Similarly, {{siteDefaults.artworksList.length}} returns 0 even though there is an entry there.

Has anyone tried to use globals before in entry URLs?

Thanks!


texts: How can I limit the rows returned in a table field?

texts:
I want to limit the rows returned here to 4, then if loop.index is 3 display a separator and then output the last row.

Does the table field have that kind of control?

{% for row in registration.registrationCost %}

{{ row.cost }}

Through

{{ row.date }}

{% endfor %}


texts:
Writing a plugin and creating some links. Trying to use:

$url = craft::$app->urlManager->createUrl(['', 'state' => 'KS']);

to create a URL. I am expecting:

  http://test.com/index.php?state=KS

but get:

  http://test.com/index.php?p=actions&state=KS

That results in the following error:

  HTTP 404 – Not Found – yii\web\NotFoundHttpException
  Template not found: actions

What is the p=actions that is being added to the url? I am a bit confused by this.


texts:
I know is kind of stupid question, but I need some 'comforting' words :)
We are going to update a very old version of Craft. We have Craft Client 2.4.2684 and going to update to the last Craft 2.6 version 2794 - 29/06/2016.

It is a very big update and usually such jumps are never going well :) What about Craft? Do the updates work good or like WP :) do they need lot of fixing of the server afterwards?

If I copy all the files present in root to my HD and a copy of the database before the upgrade, will I be able to go back without problems?


texts: Displaying Sub Categories on Category Page

texts:
First, a disclamer -- I am new to Craft CMS.

With that said, I am trying to create a category page whereby the page will show the title, description and image of the sub-categories of the current category.  It will do this so long as there are still sub-categories.  When there are no longer sub-categories it will then show the entries for that category.

I think I have figured out the code (see below), but I'm having a problem showing the images.  On one level the images show fine, but on a lower level the images are being shown in reverse order.  I can't figure out why.

Here is the code:

{% set num = 0 %}
{% set children = category.getChildren() %}
        {% if children|length %}
         {% for child in children %}

        {% set assets = craft.assets.relatedTo(children).nth(num) %}
            {% if assets %}

            {% endif %}

{{ child.title }}

{{ child.description }}

        {% set num = num + 1 %}
        {% endfor %}

            {% else %}

                {% set entries = craft.entries.relatedTo(category).level(1) %}
                {% for entry in entries %}

{{ entry.title }}

{{ entry.description }}

                Learn more
                {% endfor %}

        {% endif %}

Now, on the category page:  /topics/life/ the images are associated with the proper category.

But on the category page:  topics/life/cells, the order is reversed.  The first category displays the image for the last category and the last category dispalys the image for the first category.  Why is that and what can I do to fix it?

Thanks in advance for any help you can offer.

P.S.  Please feel free to let me know if there is a better way to code what I'm trying to do.


texts:
I have a plugin that uses its init function to save custom user data from front end registrations. It uses:

 if ($event->params['isNewUser']) {}

and

if (craft()->request->isSiteRequest()) {}

To perform front end save routines.

I want to add a small  custom user save rule for admin usage outside of the IsNewUser logic in order to preserve like this:

 if (craft()->request->isCpRequest()) {
   $user = craft()->users->getUserById($uidfromURL);
   $user->getContent()->URN = 'my custom value';
   $success = craft()->users->saveUser($user);
 }

The problem is that this code just loops thru the plugin. I need the custom field to be manually editable, but i also need to create a default value too on initial user creation in admin.


texts: Making changes to existing page - how do I make a draft page first?

texts:
I'm making extensive updates to our homepage. Before I dig in, I want to confirm the steps to create a draft without overwriting the existing page.

Select the entry that requires changes
Select "Save a Draft"
Make applicable changes
When done, click on "Current" from version drop down
When new content approved, choose the new draft in the drop down and click "Update Entry"

Am I missing something? Is there something I should do differently?


texts: Can I capture the users intent ('Save' vs 'Save and continue editing') for craft()->on('entries.saveEntry'

texts:
I'm writing a plugin that gathers up all the assets from an entry and saves it out as a zip (along with a JSON file with information from the entry).  Any advice regarding a better method is appreciated, but right now I add the code in on('entries.saveEntry'), like so:

    craft()->on('entries.saveEntry', function(Event $event) {
        $entry = $event->params['entry'];
        $outputArray = array();

        /*
        business logic filling variables removed for the sake of brevity
        */

        if (($entry['sectionId'] == 3) && ($entry['buildPage'] == 1)) {
            file_put_contents(getcwd()."/build/videos.json", json_encode($outputArray));

            $assetGroup[] = getcwd()."/build/videos.json";
            $zipfile = craft()->buildPage->create_zip($assetGroup, $entry['uri'], getcwd()."/build/");
            $filename = substr($zipfile,strrpos($zipfile,'/')+1);

            if (file_exists($zipfile)) {
                craft()->request->sendFile($filename, file_get_contents( $zipfile ), array('forceDownload' => true), false);
            }
        }
    });

Everything works, except that my sendFile call prevents the user from being returned to the Entries page (or stating a new entry, etc.), if that was their intent.  Is it possible to capture where they were headed before I stopped them, so that I can send them on their way?  Or is that not possible the way I have things written?


texts:
Any way to turn cookies off for the front end?

I think it's only CraftSessionId being set, but still, anyone know?

Cheers,


texts:
After a finally returning to an extensive recode of my first commercial Craft based site, I have successfully implemented several new (to me) features from the latest builds. One thing I am making extensive use of is entry types.

To make it easy to update my layouts, I have a section called "Widgets". Each widget entry simply points to a template file via an assets select. Presently I have three kinds of widgets: a side bar widget (Which is more compact as the name would suggest), a primary (much larger widget), and a full page widget. To keep things organized, I am sorting this based on three entry types.

So each page of my site (ex: site.com/blog) is part of a structure, which inside the structure is a Matrix field. This allows me to insert inline text, images, and the previously mentioned widgets via a related entry, though there is one major problem... I cannot seem to limit the Widget block in the Matrix field based on entry types.

My workaround I suppose would be to have 3 separate sections: one for each type of Widget, but that solution is far from elegant. SO, any ideas, guys? Here's to hoping that this would be a fairly minor update that could make it out in an upcoming release... Thanks in advance guys!


texts: Staging / Production w/ common DB and Assets

texts:
I'm hoping to implement staging and production installations for a larger scale Craft project I'm working on. My plan is to have the following structure:

/staging.domain.com
-- Complete Craft Installation

/domain.com
-- Complete Craft Installation
-- Image Assets

Updates would get done on my local server and then pushed to the staging domain, and finally cloned to the production domain. The two would share the same database and images would live on the production URL. This would allow me to see client updates to content while I make changes to templates and presentation files. I would also be able to make and test Craft software updates in the background.

From reading the documentation I would use the Sites settings to add in both domains and then set variables (dev mode, for example) in the general.php config file.

Does this sounds like a proper set up for this situation?

One optional additional change would be to move image assets off the production server and onto their own (cookieless) domain...

Many thanks in advance!


texts: Contact Form Plugin: Validate if a checkbox is checked?

texts: What is the cleanest way to validate if a checkbox (i.e. agree to legal terms) is checked?


texts:
When I try to install Craft CMS 3 by going to /admin the site redirects me to /index.php?p=admin/install where the Begin button shows. Clicking next send me to the screen to create an admin user.

When I enter all the information I see an ajax call going to http://domain.com/index.php?p=admin/actions/install/validate-account but that responds with 400 Error.

Any idea whats wrong? I have .htaccess file in place, so not sure why I see the index.php part in the url. Any help would be appreciated.
Edit: in the error log file I see those three lines

[-][-][error][yii\i18n\PhpMessageSource::loadMessages] The message file for category 'yii' does not exist: /home/rrznjzkn/public_html/craft3/craft/app/vendor/yiisoft/yii2/messages/en-US/yii.php Fallback file does not exist as well: /home/rrznjzkn/public_html/craft3/craft/app/vendor/yiisoft/yii2/messages/en/yii.php

[-][-][warning][craft\app\web\ErrorHandler::handleException] 400 - Unable to verify your data submission.

[-][-][error][yii\web\HttpException:400] exception 'yii\web\BadRequestHttpException' with message 'Unable to verify your data submission.' in /home/rrznjzkn/public_html/craft3/craft/app/vendor/yiisoft/yii2/web/Controller.php:110


texts: Removing or hiding certain fields from the CP new entry for a specific user group

texts:
I'm trying to make some fields unavailable for a certain user group when they create or edit a new entry. These fields should only be available to admin users.
I had implemented this by extending the craft\services\Fields class and using the getFieldsByLayoutId method, checking the user and unsetting the fields which should not be available for the specific user group.
This used to work but after some craftcms updates it seems to break the application.
Any ideas on how I should approach this?


texts:
So I'm setting up a multi-lingual site for the first time, and I'm having some problems with the urls.

I followed the guide, step by step. I've set up the siteUrl in general.php:

'DEV' => array(
    'devMode' => true,
    'siteUrl' => array(
        'no' => 'http://teknologi.dev/no/',
        'en' => 'http://teknologi.dev/en/',
        'es' => 'http://teknologi.dev/es/'
    ),
),

And I guess that works, since I get a message in General settings that the siteUrl has been defined elsewhere.

Then I have a section called "Videos", which I've set up like this:

And when I list out all the entries, the URL to one entry looks right, but I'm getting a 404. If I however change the Entry URL Format to include the locale letters, ex: no/videoer/{slug}, it works. But that makes the URLs write out the locales twice, so a URL might look like: http://teknologi.dev/no/no/videoer/orkanger, which of course gives a 404.

So is there some step I've missed?

Edit: I also have this structure in my www folder:

- .htaccess
- index.php // I needed this one for admin to work?
- no/
  - .htaccess
  - index.php
- en/
  - .htaccess
  - index.php
- es/
  - .htaccess
  - index.php

And in each of the localized index files I have changed the craftPath and the CRAFT_LOCALE

$craftPath = '../../craft';
define('CRAFT_LOCALE', 'no');

While the root index.php points craftPath to ../craft.

Edit 2: I tried deleting the root index.php, and while /no/ still worked, every subpage (ex: /no/videoer/) gave this error message:

The requested URL /index.php was not found on this server.

Do I need to do anything in my .htaccess for locales?


texts: System language, can I change it after installation?

texts: I have Craft on local (Pro edition) that was installed with French as the system language.  Is there a way to change to another language (English for example) for the control panel? I want to change the system language, not the content of my entries (localisation).


texts: provide a 'back' or 'cancel' or 'close' button to return to whatever page that particular template was accessed from

texts:
I have two templates. For the purpose of this question lets say the first template is step 1, and the second is step 2.
There are links to launch these templates all over the site, but some times an entry is defined and sometimes its not. if the entry is defined, step 1 is skipped.
On both steps I have a 'close/cancel' button. I need these buttons to go to whatever url the user was on when they 'launched' this process.

Is there a way of storing a URL as a variable when the 'launch' button is clicked even after moving from step 1 to step 2?

see user journey diagram:


texts:
I just created my first Craft 3 plugin. In the plugin I also have a custom (select)field. Everything is working as expected, which is great!
But I can't for the life of me figure out, how to add this field as a Table Column? It's not showing up. The field is added and filled in the entries within the section. Just to be clear, this is where I mean:

Thanks in advance!


texts: How Do I Add a rel="canonical" HTTP Header to Embedded PDF Files?

texts:
I'm working on project where I would like to directly embed PDFs onto web pages. We'll be using Google's PDF viewer as the embed tool and implementing via a macro.

Here is the macro as it stands now:

{% macro pdfEmbed(pdfLink, width="580", height="480") %}

    <iframe src="https://drive.google.com/viewerng/viewer?embedded=true&url={{ pdfLink }}" width="{{width}}px" height="{{height}}px"></iframe>

{% endmacro %}

For SEO purposes, I'd like to set a rel="canonical" on the PDF to point to the entry on which the PDF is embedded so Google knows to index the parent page and not the PDF. From what I've read, the general best practice for how to do this with embedded PDFs is via HTTP headers. See here for more detail: https://moz.com/blog/how-to-advanced-relcanonical-http-headers

I'm struggling with how to implement it in practice. I think the best method would be to use {% header %} tag within the macro but I'm not sure if there's a way to target that at just PDF files? If that doesn't work, .htaccess could be an option but then I lose the ability to dynamically set the canonical on the PDF based on the URL of the entry that houses the PDF.

What is the best way to do this in Craft? I’m running a Craft 3 site FYI.

Thanks!


texts: Search results with partial match to query

texts:
I have entry titles that contain dashes (i.e. ABC-123). When I search for 'ABC', 'ABC-123', 'ABC 123', '123' etc the entry is shown in the results (I have fuzzy search enabled). However, when I search for 'ABC123' or anything with the dash omitted from the query the entry does not appear in the results. The same goes for misspellings (i.e. 'ABB-123').

Is there a way for search to return a result that is only a partial match to the query to take into account slight differences between the query and a page title?

Please note that I have the following fuzzy search config settings:

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

And I have the following search query template code:

{% set query = craft.request.getParam('q')|replace('/(( )+|(\\n)+)/', ' ')|split(' ')|join(' OR ') %}


texts: Import CSV with FeedMe - multiple categories

texts:
I'm attempting to use FeedMe to import a CSV list of entries exported from Google Sheets. I have a column labeled "Categories" and an entry with category1,category2 as the value. I set up the feedMe job pointing to the CSV and the categories field to point to this column. However it is not importing/creating two categories (the expected behavior)rather it is just creating one category  with the name "category1,category2" -- am I doing something wrong as far as how to list out multiple categories in CSV? Can Feedme handle a comma separated list like this?
If I convert the sheet to a json, it produces: "Categories": "Category1, Category2" which does not work either - however if I edit the json to be "Categories": ["Category1", "Category2"] that works - but manually editing it is not really an option on my final spreadsheet as it will have over a 1000 entries.
If there's an easy way to convert the sheet/csv to correct Json I'd be open to that too.
Any help would be appreciated.


texts:
I am making a condition to use a certain template for a specific article category, but it's not working and giving me an error.

{% extends "_layout" %}

{% set title = category.title %}

{% block head %}
{% endblock %}

{% block content %}

    {% if category.postType=="video" or category.videoLink|length%}
        {% include 'news/hiwar.html' %}
    {% elseif category.postType=="file" %}
        {% include 'news/file.html' %}
    {% else %}
        {% include 'news/articless.html' %}
    {% endif %}

{% endblock %}


texts:
I'm fiddling around with Twig and CraftCMS, trying to create a component-based structure... of sorts.

All good so far, except this one thing I got stuck on.

Here's an excerpt from my main layout:

<body>
    {% include 'components/header.twig' %}

    {% block content %}
        woops...
    {% endblock %}

    {% include 'components/footer.twig' %}
</body>

Which currently works.

But, I'd like to do something like this...

<body>
    {% include 'components/header.twig' %}
    {% include 'components/main-wrapper.twig' %}
    {% include 'components/footer.twig' %}
</body>

Where the main-wrapper.twig is like this, for example:

<main class="main">
    {% block content %}
        woops...
    {% endblock %}
</main>

But it does not work. "woops..." from main-wrapper.twig is displayed.

I've tried a different route without success as well:

<body>
    {% include 'components/header.twig' %}

    {% embed 'components/main-wrapper.twig' %}
        {% block children %}
            {# I want to have the block content here... #}
        {% endblock %}
    {% endembed %}

    {% include 'components/footer.twig' %}
</body>

Where the main-wrapper.twig has a block named children instead... but no dice.

It does appear that what I'm trying to do is not possible, which is why I'm asking here as a last resort :)

EDIT:

For those interested, here's what I ended up with, stripped for clarity:

{# default.twig - default layout #}

<!DOCTYPE html>
<html>
    <head>
       ...
    </head>
    <body>
        {% include 'components/header.twig' %}
        {% block wrappedContent %}{% endblock %}
        {% include 'components/footer.twig' %}
    </body>
</html>

{# regular.twig - base page referred in the admin panel #}

{% extends "components/main.twig" %}

{% block content %}
    --- stuff for a page ---
{% endblock %}

{# main.twig - wrapper component! :D #}

{% extends "layouts/default.twig" %}

{% block wrappedContent %}
    <main class="main">
        <div class="main__wrapper">
            {% block content %}
                wooops...
            {% endblock %}
        </div>
    </main>
{% endblock %}


texts: How do I reorder Structure entries on the front-end?

texts:
I've have a page that has a drag and drop ability to reorder a group of Structure entries (using jquery).

I see order inside EntryModel (https://craftcms.com/docs/templating/entrymodel) but it looks like Structure positioning is handled outside the EntryModel.

Once dropped and and the entries are reordered it submits to an action inside a plugin. If I reorder two entries (or any number) how do I set the new structure order?


texts: Recommended way to include API keys in a multi-environment configuration?

texts:
What is the recommended way to configure public api keys for multi-environment configurations (i.e. local, dev, stage, production)? Is there a way to set these in either the craft/config/general.php or in plugin/config.php files?

Currently I am having to include these in each of my service methods (and something similar again in my javascript files):

private function _saveStripeCustomer($account, $token = NULL)
{
    \Stripe::setApiKey("sk_test_xxxxxxxxxxxxxxxxxx");
    // ...
}

I am generally following the configuration method shown here (both multi-environment and multi-locale). And a plugin config.php as described here.


texts:
I somehow can't access the email section of settings;
/admin/settings/email

Argument 1 passed to craft\helpers\MailerHelper::createTransportAdapter() must be of the type string, null given, called in ___/vendor/craftcms/cms/src/controllers/SystemSettingsController.php on line 139

Everything is up to date, and I've tried disabling all plugins.

Any tips on how to fix this?

I don't think I previously have added any email settings to the site, so it should have been a clean slate.


texts: Template path from plugin not working from CP

texts:
I've written a plugin that sends and email to a user group on new entry save in a particular section. Most entries will be made from the front end, and the plugin is working great in that regard. However, if a user attempts to create a new entry from the CP, the plugin cannot find my designated template path and throws an error. Any help is greatly appreciated.

if ($isNewEntry and $entrySection == 'Questions')
{
    //Get all users from UserGroup
    $user_criteria = craft()->elements->getCriteria(ElementType::User);
    $user_criteria->groupId = '9';
    $users = $user_criteria->find();
    $template = '/email/question-email.html';

    //Send to each User
    foreach ($users as $user)
    {
        //Send Mail
        $email = new EmailModel();
        $email->toEmail = $user->email;
        $email->subject = 'New Question';
        $email->htmlBody = "{% extends '{$template}' %}".
            "{% set body %}".
            '

A new question has been posted by '.$entry->author->name.':

Question: '.$entry->title.'

Description: '.$entry->questionDetails.'

Attachments: '.$entry->questionAttachments->total().'

url.'" title="'.$entry->title.'">Answer Question

                        '
            ."{% endset %}";

        craft()->email->sendEmail($email);
    }
}


texts:
I have been staring at this all morning, comparing to other plugins online and cannot see why my plugin settings page never registers. I have verified the actual settings model is populated, but settingsHtml() is never called.

Anything obvious I have missed?

class Storefront extends Plugin
{
    public static $plugin;
    public $schemaVersion = '1.0.1';
    public $hasCpSettings = true;
    public function init()
    {
        parent::init();
        self::$plugin = $this;

       $this->setComponents([
        'tracking' => TrackingService::class,
       ]);

        Event::on(
            Plugins::class,
            Plugins::EVENT_AFTER_INSTALL_PLUGIN,
            function (PluginEvent $event) {
                if ($event->plugin === $this) {
                }
            }
        );

        Craft::info(
            Craft::t(
                'storefront',
                '{name} plugin loaded',
                ['name' => $this->name]
            ),
            __METHOD__
        );
    }
    public function hasCpSection()
    {
        return false;
    }
    public function hasSettings()
    {
        return true;
    }
    protected function createSettingsModel()
    {
        return new Settings();
    }

    protected function settingsHtml(): string
    {
        return Craft::$app->view->renderTemplate('storefront/settings',
            [
            'settings' => $this->getSettings()
            ]
        );
    }
}


texts: Reset admin account password using command line interface

texts: Can I reset admin password using console CLI interface? Didn't see anything like that when I run the craft file directly and it displayed list of commands.


texts: Visitor-facing pages work; admin login doesn't--I can't login in to admin

texts:
The login page has no styling, including no Powered by image. This is what displays beneath the site's title:

When I try to login I receive:

Bad Request
Unable to verify your data submission.

The site is one I moved from dev to production, from a local to remote server. I used checkit.php on the remote server and it passed. I know the paths to asset volumes are incorrect, so while public pages display properly, they do so without images, which is what I was trying to login to fix. CSS, JS, text pulled from the database--all work.

What could be wrong? Thank you in advance for any help.

[Edit]

Thank you for responding. This site is on a Namecheap Stellar Business shared hosting plan. It's an addon domain. The "web" directory is set as document root. The site's folder is above the public_html directory in the hosting account's root directory.

Yes, there are 404 errors in the console. The unfound files exist where they should, in the web/cpresources directory. The 404 paths don't include the "web" directory.

Because the web directory is set to root, won't resources in the web folder will be found even if the "web" directory doesn't show up paths? The web/index.php file is found without "web" being in the url. The site loads for visitors to the site.


texts: Separate time settings from user locale?

texts:
I would like to render the DateTime fields in the backend with european time format, even though the user I'm logged in with is set to English/US.

Is this possible?


texts: Internal Server Error - The file does not appear to be an image

texts:
On a live environment I'm hitting an error when uploading some jpg images, which wasn't a problem on dev or production.

I can get around it by re-exporting the image out and keeping it under 1mb, but as the site has a form with an upload field I need to figure out what the environment issue could be with being picky over these.
Where should I start?

This happens whenever I try to upload problematic images, not just from the front-end form field, but also directly into Crafts Assets.
The file name in the error message is also not what the actual file name is - it looks like it creates some temp name for it.

EDIT: Found out that the server doesn't have Imagick installed but has GD 7.2.17. Could this be the issue?


texts: How to make field instructions show as tooltip?

texts:
How to turn

show as the following style


texts: If Entry is related to Category-A, then print xyz

texts:
I have succussfully been able to list entries within the 'brandx' category slug, but I can't figure out a way to print specific content only if the current 'product' listing is related to the 'brandx' category.

I have tried quite a few things and have come up empty, so I feel like I'm either missing something basic, or there's a trick I can't find in the docs or here.

{% paginate craft.entries.section('shopDetails').level(1).limit(24) as postsOnPage %}
      {% for product in postsOnPage %}
           …
            <h5>
              {% set cat = craft.categories.slug('brandx').first() %}
              {% set catGroup = craft.entries.relatedTo( cat ) %}
              {% if product {# is within the catGroup #}  %}
              Brand X
              {% endif %}
              {{ product.title }}
            </h5>
{% endpaginate %}


texts: Can you host a Craft site on 1984 Hosting?

texts:
Does anyone have experience hosting a Craft site on 1984 Hosting? It's an Icelandic company whose ethos I like and I'm considering making my new site in Craft, so would be good to hear of anyone who's managed it.

https://www.1984.is/


texts: How do you get entry's data from Ajax form submission with Guest plugin?

texts: I'm trying to get some info from entry like entry ID that the Guest plugin sent it via Ajax. There are the keys that the plugin responds back with. How can I work out to those keys respectively call them? (response.id) for example?


texts:
In my plugin, I would like to search a folder.
However, I cannot find any information about the criteria for folders.
Are there any documentation or something?

$n = Craft::$app->assets->findFolder(array(
    'name' => $folder,
    'parent' => $p_folder
));

My code is like this. Folder name is not unique, so I have to also use its parent.
However, I do not know how to include parent folder in the criteria. "Parent" is not correct.


texts: Querying by lightswitch field type in template

texts:
I have a field (mdFeatured) set up as a lightswitch field type. I am trying to retrieve both featured and non-featured entries:

{% set featuredEntries = craft.entries.section('merchantDirectory').mdFeatured(true).relatedTo(category).find() %}
{% set normalEntries = craft.entries.section('merchantDirectory').mdFeatured(false).relatedTo(category).find() %}

The featured entries are being retrieved properly, but the normal entries are returning both featured entries and normal entries mixed together. Any possibly know why this is not working? I tried replacing "true" and "false" with "1" and "0" but that did not seem to work either.

Thanks!


texts:
I really want something like this to work but the merge function turns Elements into Arrays. I've managed to work around it other times but what's the best practice to combine two entry sets and then paginate?

{% set cat1 = craft.categories.group("catAttributes").slug('diabetic').one %}

{% set firstEntries = craft.entries.section("cats").relatedTo([cat1]) %}

{% set secondEntries = craft.entries.section("cats").showInOtherOnCatsWithNeeds('1') %}

{% set allEntries = firstEntries | merge(secondEntries) %}

{% paginate allEntries.limit(12) as pageInfo, pet %}


texts: Error while accessing an associative array

texts:
Here is the code:

{% if entry_name not in data and entry_total > 0 %}
    {% set data = data|merge({ (entry_name) : entry_total }) %}
{% else %}
    {% set data.entry_name = 10 %}
{% endif %}

Twig throws an error on the statement following else condition.  Unexpected token "punctuation" of value "." ("end of statement block" expected). How can I set the value of a particular element of this associative array?


texts:
So I have a few different channels for different types of content.

One called pages which is just for regular web pages. All of those entries work uppercase or lowercase so example.com/About and example.com/about both work.

The Entry URL Format for pages is

{slug}

The Entry Template is

/_page

I have a problem with a few of my channels for blog entries and I believe it is because of the Entry URL Format being used, but at the same time that doesn't make sense since it works fine for the page channel. Example channel is called Articles and the Entry URL Format is

articles/{postDate.year}/{slug}

And the Entry Template is

articles/_entry

The main Articles page which shows the index of all articles etc is using

articles/index.html

in the articles directory which is probably causing the problem.

So the problem ends up being that example.com/articles works but example.com/Articles does not and goes to a 404. Now if I am inside of a single entry it can have caps so example.com/Articles/this-is-an-Article works.

This is hosted on a linux server. Only reason I mention that is because how linux handles cases differently, on the staging server which is windows they all work fine. So not sure if I would need to setup 301's for those blog channels using the index.html files inside each channel folder. Or if there is another way of handling this. Possibly a route, or a single but I don't see why that would be needed.

I have some singles setup like this as well but they work with or without caps... so something seems odd about these channels.

Anyone have any thoughts on that.


texts: Loop through matrix field find first block of a type

texts:
I'm trying to loop through a matrix field that has a few different types of fields in it and different orders. I want to first the first field of a certain type and output only that. Here is what I have so far.

{% for block in entry.blogPostMainSection.all() %}

{% if block.type == "blogText" %}

    {% set articleText =  block.blogArticleText %}

        {% if articleText | length > 100 %}

            {% set articleTextTrim = block.blogArticleText|slice(0, 100) ~ '...' %}

            {{articleTextTrim | striptags}}

        {% else %}

            {{articleText | striptags}}

        {% endif %}

{% endif %}

{% endfor %}


texts: Get image from related entries asset field

texts:
I have a "single" entry which has a "entries" field. The related entries have a image field of the "Assets" type.

In the template, i want to display the image from each of the related entries. I figured i could do the following

        {% for relatedImage in entry.relatedImages %}
            {% for images in relatedImage %}

            {% endfor %}
        {% endfor %}

Though not only does it not work, but it is probably pretty inefficient too. Whilst I'm here, how do people go about inspecting what you get from your vars? Is there a Twig/Craft equivalent to PHP's var_dump('relatedImage')?!

Any ideas most welcome!


texts: Is there a master list of user/group permissions in Craft?

texts: Has anybody compiled (or is it be possible to extract from the system) a master list of all the various permissions one can assign in Craft?


texts:
I want to use locales like en-US instead of en_us.
Is there a way to do this other than creating totally new locales?
Can I set it up at the siteUrl ?


texts: Why is news/_entry not extending _layout?

texts:
I'm quite sure the problem is my paths to .css files in the _layout.html file but just can't get my head around it.

I've got this in my _layout.html. It works for home page and news page.

{% includeCssFile "css/material.css" %}
{% includeCssFile "css/main.css" %}

But then I get the unstyled page when viewing a specific news entry. _entry.html is not extending _layout.html

My CSS files are on the same level as my templates. What should these paths be?


texts: Combined entries from sections across locales

texts:
I'm merging entries from two separate sections across locales.
All going well but when I try to paginate the results I get the following error:

Recoverable error

Argument 1 passed to Craft\TemplateHelper::paginateCriteria() must be an instance of Craft\ElementCriteriaModel, array given,

The offending code as follows (simplified):

{% set pages = [] %}
{% set devNews = craft.entries.section('newsDevelopment').status(null).find() %}
{% set alumniNews = craft.entries.section('newsAlumni').status(null).locale('prior_alum').search('shareNewsAlumni:1').localeEnabled(false).find() %}
{% set pages = pages|merge(alumniNews) %}

{% paginate news as pages %}
    {% for article in news %}
        ...
    {% endfor %}
{% endpaginate %}

As I say, works fine/as expected without the paginate but as soon as I try to paginate I get the error.

Any thoughts on above appreciated.


texts: Best way to search users by a custom field inside a plugin?

texts:
This did work until there’s a significant amount of users:

$criteria = craft()->elements->getCriteria(ElementType::User);
$users = $criteria->search('customField:' . $someValue);

I’m using search as I need to find a value within the custom field. The field is typically 1,2,3 and I need to check for one of those values.

I have also tried to limit it without success.

$criteria->groupId = 1;
$criteria->limit = null;

What’s the best way to do this?

UPDATE:

The users getting missed are those that had the fields I’m searching populated by another plugin. This looks as though the data is not being saved in the same way as when it’s entered manually in the CP.


texts: Why does calling matrix block type before matrix block loop lead to no loop output

texts:
In the code below I am trying to check for the presence of a quote block to help define some layout columns.

As soon as i count an individual block, the loop block below it outputs nothing. If remove the column logic based on length of quote block the loop below then outputs.

{# position columns width if there is a quote #}
{% if entry.contentBlock.type('quote').limit(1) | length %}
    {% set col1 = "12u$(medium) 7u  " %}
    {% set col2 = "5u 12u$(medium)  " %}
{% else %}
    {% set col1 = "12u$(small) 6u -3u  " %}
    {% set col2 = "hide " %}
{% endif %}

 {{ entry.title }}

    {% for block in entry.contentBlock.all() %}
        {% if block.type.handle == "text" or block.type.handle == "image" %}
            {% include ('page/_partials/_' ~ blockPrefix ~ 'block_' ~ block.type.handle) %}
        {% endif %}
    {% endfor %}

    {% for block in entry.contentBlock.type('quote').all() %}
        {% include ('page/_partials/_' ~ blockPrefix ~ 'block_' ~ block.type.handle) %}
    {% endfor %}


texts:
I have a field type that needs to do some processing, based on the data in the element it belongs to, when an element (entry, category, user, etc) is saved, and save it to the field. I'm hooking into onAfterElementSave and my code (simplified) is as follow:

public function onAfterElementSave()
{
    $fieldHandle = $this->model->handle;
    $elementId = $this->element->id;
    $elementType = $this->element->getElementType();
    $elementLocale = $this->element->locale;

    $criteria = craft()->elements->getCriteria($elementType);
    $criteria->id = $elementId;
    $criteria->locale = $elementLocale;
    $element = $criteria->first();

    if ($element!==null) {
        $myData = $element->title; // just an example
        if ($this->element->$fieldHandle != $myData) {
            $newData = array($fieldHandle => $myData);
            $element->setContent($newData);
            craft()->elements->saveElement($element);
        }
    }
}

This works fine on existing entries, but when I create new entries, $element is null, so the field isn't updated.

What's going on and how can I fix this? Isn't onAfterElementSave actually after element save? :)


texts: How are parent and child categories related in Craft database?

texts:
I am writing an API which directly connects to Craft database and retrieves data.  I need to get the categories hierarchy.  But I can not find how parent and child categories are related in the database, therefore I can't write an SQL query to retrieve it.
Can anyone help with this?


texts: How can I add custom headers to an ElementAPI response?

texts:
I need to add the a custom header to the ElementAPI endpoints I setup but I want to avoid editing the source of the plugin. What is the best way to go about this?

The ElementAPI plugin returns some default headers by using:

JsonHelper::sendJsonHeaders()

To quickly achieve what I needed I added the following to the ElementApiControllor.php:

HeaderHelper::setHeader(['Surrogate-Control: max-age=300'])

This works for now but I'd love to learn how to extend existing plugins that don't have any documented hooks with my own if it is possible.


texts: Wanting to move static/single templates in to a directory pages and thus, the path to my 404 template is now pages/404.html. I don't necessarily need dynamic content as asked here. Is there a config setting I can use to point the default 404 URI behavior to that template?


texts:
I’m trying to sort entries from a section called exhibitions by startDate and then by the title field of a related gallery entry. So  exhibition entries with the same entry.startDate are ordered alphabetically by entry.gallery|first.title if you will.

I know I can use SQL statements in the order attribute for craft.entries.section('exhibitions').order('...'). Is it possible to achieve something similar to the answer given in https://stackoverflow.com/questions/10786849/sorting-with-related-tables-in-mysql with the craft.entries API from a twig template?

The other solution I discovered was using a Preparse Field and have it save the gallery|first.title on the exhibition entry and then query entries like this: craft.entries.section('exhibitions').order('startDate, galleryTitle'). I would prefer not to use this trick however.

Thanks in advance for any suggestions on this topic.


texts: How to create an entry from plugin controller?

texts:
Let's say I have a section 'foo', with following fields and slug:

First Name (name)

Last Name (lname)

Plan (plan)

Cost (cost)

The field cost is dynamically created by a function already present in controller. I tried the following:

public function actionGetCost()
{
    $fname = craft()->request->getParam('name');
    $lname = craft()->request->getParam('lname');
    $plan = craft()->request->getParam('plan');

    ...

    $entry = new EntryModel();
    $entry->sectionId = 16;
    date_default_timezone_set('America/New_York');
    $date = date('n-j-Y') ;
    $entry->postDate = $date;
    $entry->authorId = 1;
    $entry->enabled = true;
    $entry->setContentFromPost([
       'name' => $fname,
       'lname' => $lname,
       'plan' => $plan,
       'cost' => $cost->id,
    ]);

    $save = craft()->entries->saveEntry($entry);

    if ($save){
      echo "saved" !
    }else{
      echo "<pre>";
      print_r($entry()->getAllErrors());
      echo "</pre>";
    }
}

What's wrong in the code? How can I do it?


texts: Getting a entry link created by current User

texts:
I am trying to create a link that would allow a logged in user to access their profile from the front end. Basically, the user has one page they can edit from the front end when logged in, and I'd like to link to that page in the navigation. I've seen similar things done in Craft 2 but not in Craft 3. So far I tried this: but it didn't work.

{% set myEntry = craft.entries.section('userProfiles').authorId(currentUser.id).limit(1) %}
My Profile

as well as..

{{ myEntry.limit(1).url() }}

Thank you!


texts: Redirect user based on group after Craft login

texts:
I have a plugin that checks for the current user on login and should redirect the user if they are part of a particular user group. When I do this I get the following "An unknown error occurred." and the redirect doesn't work. See init function below:

function init()
{
    craft()->on( 'userSession.onLogin', function( Event $event ){
        $user = craft()->userSession->getUser();
        if ($user && $user->isInGroup('sales')){
          $url = "new.url";
          craft()->request->redirect($url);
        }
    });
}

Please advise.


texts: How can I base64-encode an Image Transform?

texts:
I'm trying to use this plugin, but it requires an AssetFileModel as input. I can pass it the asset in question, no problem, but I'm wanting to pass it a transformed version of the asset. However, it seems like there's no way in Craft to pass a transformed image as an AssetFileModel.

Here's my code:

{% set image = assetField.first() %}

{# Doesn't work; `image.url({width: 40})` outputs a URL as a string, not an AssetFileModel #}
{% set imageTiny = image.url({ width: 40 }) | image64(true) %}

...

The desired result is for a base64-encoded string of the tiny, 40px-wide image to be output in the HTML.

Any ideas?


texts: Is there a way to get a variants stock quantity in commerce?

texts:
Like the question says. I know you can check if a variant is "in stock" with v.hasStock, but is there a way to pull the current stock quantity value?
In my particular situation I would like to do something like this:
<input type="number" min="0" max="{{ variant.availableStock }} />
So as to prevent users from inputing a quantity that the store doesn't have.


texts: Craft hangs when saving any entry and brings Apache down

texts:
Everything works fine on my local machine (OSX/MAMP PRO) but on my server (Digital Ocean LAMP stack on Ubuntu) saving an entry brings the whole thing down and I have to restart Apache before the site becomes responsive again. It doesn't seem to time out, it just never completes the save. Oddly, it does actually save the data so when I bring the server back up with service apache2 restart the changes are there.

Apache logs look like this:

zend_mm_heap corrupted
zend_mm_heap corrupted
[Mon Nov 03 11:44:55.395173 2014] [mpm_prefork:notice] [pid 16677] AH00169: caught SIGTERM, shutting down
[Mon Nov 03 11:44:56.453282 2014] [mpm_prefork:notice] [pid 17116] AH00163: Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.4 configured -- resuming normal operations
[Mon Nov 03 11:44:56.453484 2014] [core:notice] [pid 17116] AH00094: Command line: '/usr/sbin/apache2'
zend_mm_heap corrupted
zend_mm_heap corrupted
[Mon Nov 03 11:51:53.601504 2014] [mpm_prefork:notice] [pid 17116] AH00169: caught SIGTERM, shutting down
[Mon Nov 03 11:51:54.577982 2014] [mpm_prefork:notice] [pid 17178] AH00163: Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.4 configured -- resuming normal operations
[Mon Nov 03 11:51:54.578223 2014] [core:notice] [pid 17178] AH00094: Command line: '/usr/sbin/apache2'

The zend_mm_heap corrupted bit looks like it could be something to do with it? I've tried increasing out_buffering as per this SO thread but it didn't help. I don't know where to even start with this, I've never experienced it before.

Apologies if this is a bit vague but this is the only place I can think of to ask — I've contacted P&T too.

EDIT: I've re-installed a new version of Craft in the same place on my server and, although the installation went 'Oops' I can actually log in and save entries so I don't think there's anything fundamentally wrong there.


texts:
Using this fantastic article on validation, I have written a custom validator class. Everything is working, but I'm curious about the rules and defineAttributes method(s). Most likely I'm just misunderstanding how it all works.

MyModel.php

    public function defineAttributes()
    {
        return array(
            'firstName' => array(
                'type' => AttributeType::Name,
                'required' => true
            ),
            'lastName' => array(
                'type' => AttributeType::Name,
                'required' => true
            ),
            'email' => array(
                'type' => AttributeType::Email,
                'required' => true
            ),
            'phone' => array(
                'type' => AttributeType::ClassName,
                'maxLength' => 14
            )
        );
    }

    public function rules()
    {
        $rules = parent::rules();

        $rules[] = ['email', 'Craft\MyPlugin_EmailValidator'];

        return $rules;
    }

Do I really need both? I (thought) that defineAttributes was the rules method. Everything is working properly; I'm doing a check to make sure the email is unique. I have a unique key defined on the record as well.

Thank you!


texts:
From a custom plugin controller, I am returning data as json using $this->returnJson($data). I need to be able to set the Cache-Control headers for my forward cache proxy to handle caching correctly.

I tried using HeaderHelper::setExpires(300), but JsonHelper::sendJsonHeaders(), which is called by $this->returnJson() from the controller, overrides setExpires by calling HeaderHelper::setNoCache().

Does anyone have any ideas for working around this or configuring returnJson? I can do the following in my controller (or create a helper of my own):

HeaderHelper::setExpires(300);
HeaderHelper::setContentTypeByExtension('json');
ob_start();
echo JsonHelper::encode($return);
craft()->end();

but I'd rather use the super convenient returnJson function.


texts: How to add multiple performers to event schema with seomatic

texts:
I am adding event schema to an entry page. I have offer and date properties working well based on https://nystudio107.com/blog/tips-for-using-seomatic-effectively

This is working for offers

{% if entry.soldOut == '1' %}
  {% set availability = 'http://schema.org/SoldOut' %}
{% else %}
  {% set availability = 'http://schema.org/InStock' %}
{% endif %}
{% set offersJsonLd = seomatic.jsonLd.create({
    'type': 'Offer',
    'price': entry.eventPrice,
    'priceCurrency': 'GBP',
    'validFrom': entry.postDate|date("Y-m-d"),
    'url': entry.url,
    'availability': availability,
}, false) %}
{% do mainEntity.offers(offersJsonLd) %}

I can't work out the correct approach for performers though. I have a Matrix field for performers with two fields performerType and performerName

I have tried this

{% set performerJsonLd = seomatic.jsonLd.create(
  {% for block in entry.performers .all() %}
    {
    'type': block.performerType,
    'name': block.performerName,
    },
  {% endfor %}
  false) %}
{% do mainEntity.performer(performerJsonLd) %}

and

{% set performersAndTypes %}
  {% for block in entry.performers .all() %}
    {
      '@type': '{{ block.performerType }}',
      'name': '{{ block.performerName }}',
    }{% if not loop.last %},{% endif %}
  {% endfor %}
{% endset %}
{% set performerJsonLd = seomatic.jsonLd.create(
  performersAndTypes,
  false) %}
{% do mainEntity.performer(performerJsonLd) %}

but get errors for both.

What would the correct approach be to get this working?


texts: Select Transform Feature with Asset Field

texts: If you insert an image in a Rich Text field you get an option to apply a transform, but that is not true when using an Asset field to choose an image, which seems strange. Is there any way to accomplish that?


texts: How to exclude a Matrix block from search?

texts:
I'm using a Matrix field as a content builder, allowing the editor to freely create content blocks, titles, images, etc, etc. All of which is content that is required to be searched. But also included in there is an entries fields allowing the editor to select related content to appear within the page content. Because the search control ("Use this field’s values as search keywords?") is on the whole Matrix field, this related field is also getting scooped up in the indexing, which means entries are appearing in search results based on their related entries content, not their content.

Is there a way to exclude from search a specific block/field type from within a Matrix field?  Or exclude related entries?

Possibly enhancing the search query (current code below)...?

        {% set searchResults = craft.entries()
            .section('articles')
            .search(searchQuery)
            .slug('and, not __home__')
            .orderBy('score')
            .all() %}

Or a way to parse the results without it dragging down performance? Although this will render score useless.

The other option I've considered is to rebuild the whole site moving the content to utilise Neo fields which might allow search control specific to each field within the Neo Matrix (need to explore & confirm).

Here's the Matrix field, the linkedContent and globalBlock are the offending fields polluting the search, but can't be removed from the Matrix, as then they wouldn't be able to be placed into the middle of content pages.

Update 1: Tried editing the database fields table, changing the individual field's "searchable" column to false and re-indexed but assume it's ignored (or just honors the parent Matrix field setting), as search results still include the offending entries field.

Update 2: Leading on from previous update, I explored the code and it is a minor amend to the Matrix field code to enable/disable searching of individual blocks within the Matrix. I've posted a bug fix/change request here which also includes the partial solution.


texts: Is it possible to output Profiling Summary Report (devMode)

texts:
Is it possible to output Profiling Summary Report when in devMode? Looking to print this out onto a template:

Time:   0.36980s
Memory: 20,563Kb
Total Queries: 19


texts: How can I use slim templates with Craft?

texts:
Coming from ruby and rails, I’ve been using slim (https://slim-lang.org) for years. It’s brevity and clarity have become the norm to me and writing and reading  full html feels a bit exhausting.

I am wondering, is there a way to use slim with twig templates in Craft? Does anyone here use this combination? Would you be willing to share your setup?

Thank you!