texts: Use query string with relatedTo() with categories inside a category group

texts:
I have created a test category called test inside the what-we-do category group. There are three files at play

The first has a line of code that generates the query string on button click

{% for cat in categories %}

{{ cat.title }}

{% endfor %}

The second takes the query string formats it and passes it to the list template. The code looks like

{% if craft.request.queryStringWithoutPath %}
    {% set categoryQueryString = craft.request.QueryStringWithoutPath| replace({"category=" : ""}) %}
{% else %}
    {% set categoryQueryString = "" %}
{% endif %}

    {% include '_includes/snippets/blog/list.html.twig' with {category : categoryQueryString} %}

Then the list code looks like

{% set sections = 'blogPosts' %}
{% paginate craft.entries.section(sections).relatedTo(craft.categories.slug('what-we-do/' ~ category|default)).limit(limit) as pageInfo, pageEntries %}

{% for entry in pageEntries %}
    {% if entry['listingPageText']|default %}
        {% set content = entry.listingPageText %}
    {% endif %}

{{ content }}

{% end for %}

This section seems to be working when I dump it but I am not seeing any of my entries rendered

{% paginate craft.entries.section(sections).relatedTo(craft.categories.slug('what-we-do/' ~ category|default)).limit(limit) as pageInfo, pageEntries %}

I'm wondering if there is something simple i'm missing

If I use

{% paginate craft.entries.section(sections).relatedTo(category|default).limit(limit) as pageInfo,pageEntries %}

I can get the posts to appear but it does not filter by category it just defaults and renders all the blog posts.

I'm guessing that's because I have to pass the full category url what-we-do/test assuming the category name is test.

What I really need is it to show the blogposts that are of category test inside the category group what-we-do


texts:
The following doesn't assign an existing user to a group. I've confirmed that both the user and the group exist. Any ideas?

$user = User::find()->username($username)->one();
$user->setGroups([Craft::$app->userGroups->getGroupById(1)]);
Craft::$app->elements->saveElement($user);

I found this answer, which will probably solve it for me, but it leaves me wondering what the purpose of setGroups is.


texts: Will having large numbers of Fields decrease site performance?

texts:
I know that on page load Craft makes multiple queries to get Fields. I have about 300 separate fields on a pretty large site. I know it's probably better to reuse fields when I can, but in many cases I can't rename fields or field instructions so I wouldn't be able to name them semantically for the user.

Is it OK to have this many fields on my site, or should I find another strategy to manage my large number of fields, many of which are very similar?


texts: How can I group a list of tags into ranges of first letters (A–E, F–J, etc.)?

texts:
I'd like to be able to fetch a list of tags from a blog section and then group them into ranges of letters.

I've used this code to fetch and group a list of tags by first letter:

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

{% set allTags = craft.tags.relatedTo({
  sourceElement: entries
}).order('name').limit(null) %}

{% set allTagsGrouped = allTags|group('name | first') %}

But what I'd like to do is to have groups for ranges of first letters like A–E, F–J, etc.

The end goal is to create an index of all of the tags in use, but group them under ranged letter headers instead of individual letter headers.

How would I go about doing this?

Thanks!


texts:
For a url like domain.com/example/123 where 123 is a Matrix Block ID (not an Entry ID), can I get the associated entry for given block ID in a template?

Or, for a more general approach, what would be the best way to get that Matrix Block element and its Entry element when you only have a block ID?

Edit: so ideally:

{% set block = craft.matrixBlocks.id(craft.request.segment(2)).first() %}
{% set entry = block.getOwner() %}

...which isn't possible now.


texts:
We built a small conference site last year that had a Speakers channel. At the time, we used the title field to store the last name of a speaker. That was fine but for editors, where there are speakers with the same last name, it's become confusing.

So I thought we'd be able to switch to using title format of {title}, {speakerFirstName}

This works but involves having to resave the entries which isn't a huge deal but would be great if there was a way to update these all at once?


texts:
Just figuring out the craft interface and finding all sorts of useful features. Just can't figure out what the purpose of "categories" is in the settings.

Would be much appreciated if anyone could please tell me how this function is intended to be used and set-up?

Thanks!!


texts:
I have a structure that I am using for a schedule, it has 1 entry per day (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday).

What I want to do is only show the 3 days from the current day.

i.e if today is Thursday, it will show the Thursday, Friday & Saturday entries.

I have used the following to control the offset which works great.

{% for entry in craft.entries.section('schedule').offset(now|date('w')).limit(3).find() %}

My problem is, when I get to Friday or Saturday it wont show Sunday because that is the first entry of the structure.

Is there anyway I can have it loop around to start the list of entries again?


texts: Smart Map - How to search by a field in address?

texts:
I have entries using the Smart Map address field. I need to get just the entries that have a combination of city and state (city = "Beverly Hills" AND state = "CA"). I am currently only trying to get simpler search state working and only then will I move to state/city. I can get a "fuzzy" that to my understanding will get everything that has "CA" in any of the fields using:
{% set meetings = craft.entries.section('meetings').search('address:' ~ 'CA') %}

But I want to understand how to create a more specific search that specifically finds 'CA' in address.state.
When I try:
{% set meetings = craft.entries.section('meetings').search('address.state:' ~ 'CA') %}

the search returns nothing. No errors either.
Questions:

How do I search specifically in a field like address.state?
Extending this question, how do I search address.state AND address.city?


texts: 302 redirects to locales in main index.php

texts:
I have written this simple redirect code in the main index.php file.
Now I need to know if this code can somehow cause problems with Craft:

    // Check if URI contains cpTrigger
    $pos = strpos($_SERVER['REQUEST_URI'], 'admin');

    if ($pos === false) {

        // Language paths
        $paths = array(
            'de'=>'/de/',
            'it'=>'/it/',
            'en'=>'/en/'
        );

        // Browser language
        $language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

        // Default language
        if (!isset($paths[$language])) {
            $language = 'de';
        }

        // Redirect
        header('HTTP/1.1 301 Moved Permanently');
        header('Location:' . $paths[$language]);

    } else {

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

        // Do not edit below this line
        $path = rtrim($craftPath, '/').'/app/index.php';

        if (!is_file($path)) {
            exit('Temporary error. Could not find the CMS folder.');
        }

        require_once $path;

    }

Only the 404 page doesn't load with www.example.com/idontexist but loads instead the homepage.
(www.example.com/en/idontexist loads as expected the 404 page)

Perhaps somebody knows a better solution?


texts: Pagination: Next/Previous related to author

texts:
I'm having trouble limiting next/previous links in one channel to articles by the author.

next/previous links are working correctly on the regular blog but when included on the DJ blog I get unknown property errors in the template.

If I remove the merge line below pagination appears to work, but includes DJ posts not by the current Dj.

url looks like https://domain.com/djs/503/firstName-lastName where 503 is the author.id

{# Set parameters for prev/next elements list #}
{% set params = craft.entries.section(channel).orderBy('title asc') %}

{# if djs channel limit to author based on url segment 2 which is author id #}
{% if craft.app.request.segment(1) == 'djs' %}
  {# get dj to relate and limit next/prev #}
  {% set author = craft.app.request.getSegment(2) %}
  {# {% set dj = craft.users.id(author).one() %} #}

  {# {% set params = craft.entries.section('djBlog').relatedTo(author).orderBy('title asc') %} #}

  {% set params = params | merge({ relatedTo: author }) %}

{% endif %}

Below code is working on all other templates except the DJ blog where I need to restrict pagination to posts by the current author. Only including here in case it may be relevant though I don't think so.

 {# grid-container #}

      {% if prevEntry %}

          {##}
          {{ macros.icon("next", "icon-blue", "40", "40") }}
           Previous

      {% else %}

          {##}
          {{ macros.icon("next", "icon-blue", "40", "40") }}
           Previous

      {% endif %}

      {% if backTo == 'true' %}

          Back to {{ backToTitle }}
          {#  #}

      {% endif %}

      {% if nextEntry %}
        Next{{ macros.icon("next", "icon-blue", "40", "40") }}
      {% else %}
        Next{{ macros.icon("next", "icon-blue", "40", "40") }}
      {% endif %}


texts: Dashboard icons missing with flexible SSL

texts:
We are enabling SSL initially via cloudflare and their free flexible SSL. This works great for the site content, but on the dashboard for craft, if I login, any icons are converted into words.

https://www.cloudflare.com/ssl

I am seeing that the page is serving mixed secure content, but wonder if there is a way to make craft happy with this situation and render the font icon properly?

We will eventually implement a full SSL cert, but this will be in place for a while.

Many thanks :)


texts: How to speed up a single entry page with Eager Loading

texts:
This is a single entry page. I have an assets field of imageGallery which allows multiple images to be uploaded but it could also be empty. I want to use the first image at the top of the page (if one exists) then show the rest of the images (if there is more than one) excluding the first one after the bodyText field. I'm also loading a transform named 'gallery' if the original image is larger than the transform. This is the code I have now (simplified for clarity):

{% set titleImage = entry.imageGallery[0] ?? null %}

{% if titleImage|length %}
    {% if titleImage.getWidth()>titleImage.getWidth('gallery') %}
        <img src="{{ titleImage.url('gallery') }}"
    {% else %}
         1 %}
    {% for image in entry.imageGallery.offset(1).all() %}
        {% if image.getWidth()>image.getWidth('gallery') %}
            <img src="{{ image.url('gallery') }}"
        {% else %}
            <img src="{{ image.url }}"
        {% endif %}
    {% endfor %}
{% endif %}

How could this be impoved on for faster loading?


texts: Automatic cache clearing when reordering custom element type

texts:
I've developed a custom menus plugin which has been working great

https://github.com/familiar-studio/craft-menus

Im trying to get it work with the build in template caching and realizing the reorder actions are not triggering the caches to clear properly?

The template is using the "getNodes(menuHandle)" variable
https://github.com/familiar-studio/craft-menus/blob/master/menus/variables/MenusVariable.php

which just uses standard element criteria? We are also using native structures so is there some way to specifically tell it to clear on reordering as well?

UPDATE: here is the code thats in my _layout that im hoping will clear when i reorder or add new elements

{% cache %}

      {% nav node in craft.menus.getNodes('utilityMenu') %}

                {{ node.title }}

            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

     {% endnav %}

{% endcache %}

UPDATE 2: So on deeper investivation it appears that the issue is only that it doesnt clear the cache when the structure is reordered, editing and saving nodes seems to clear it after all.


texts: Emoji mb_detect_encoding() error when updating to latest Craft 2.6.x

texts:
I updated a Craft 2.6 installation to the latest 2.6.x and suddenly I get an error when saving a user's profile on the frond end:

mb_detect_encoding() expects parameter 1 to be string, array given
/data/sites/web/boumaticdevbuthostcom/subsites/corporate-web.boumatic.dev.buthost.com/craft/app/vendor/elvanto/litemoji/src/LitEmoji.php(108)

However, nowhere on that page has an emoji been inserted in any input fields or anything.

I hope somebody can help me with this as it is an urgent issue.

UPDATE

I just tracked down the problem to this input field:

<input type="hidden" name="fields[gdprPermissionsList][permissionSales][type]" value="permissionInfo">

Which is quite weird as it does the exact same thing as 3 other fields on that page which work fine.


texts: Craft license: what is considered a "dev-sounding subdomain"?

texts:
On the license enforcement help page, it says there are a number of checks to determine whether or not a domain is public. One of those checks is the following:

Does it have a dev-sounding subdomain (e.g. ‘dev’, ‘local’, ‘loc’, ‘test’, ‘testing’, ‘stage’, or ‘staging’)?

My question is, is there a sure-fire way of determining whether or not a subdomain is dev-sounding? For instance, what if my subdomain has the string 'staging' (e.g. http://staging-subdomain.mysite.com). Or what if it was just an unconventional sounding subdomain (e.g. http://www-next.mysite.com)?


texts: Users creating their own custom subscription or bundle in the frontend?

texts: I am trying to add a feature to a store (using Craft Commerce 3) that allows users to create their own subscription or bundle by selecting which products they want to buy and choosing the frequency. Is there a way this can be done?


texts: Pass content of system messages to HTML Email Template

texts:
I know I can set the template in the email settings to use a HTML template but how do I pass the content of the system messages (activate your account, reset your password, etc) to this template?

I've added this to the html template but then the email that is sent is blank:

{% block content %}
{% endblock %}


texts:
I have a plugin where I'm creating custom entries based on user submitted data. Saving these entries works well. As does modifying their titles after saving to add the entry's ID to the title (using craft()->on('entries.saveEntry', function(Event $event) { ... }). The problem I'm having now is that I'd like to also update the slug at this point, so that each entry's slug is just its ID.

I've tried using:

$entry->setContentFromPost(array(
    'slug' => $entryId,
));

and

$entry->getContent()->slug = $entryId;

but neither do anything — even though the title change is getting saved successfully. Either I'm missing something, or the slug is handled differently than both entry fields and entry base content.

My question: How do I update the entry slug from a plugin to be just the entry's ID?

Here's the code I currently have in my plugin's base class:

public function init()
{
    craft()->on('entries.saveEntry', function(Event $event)
    {
        $entry = $event->params['entry'];
        $entryId = $entry->id;

        $newTitle = str_replace('Name: ', $entryId . ' - ', $entry->title);

        $entry->getContent()->title = $newTitle;

        $entry->setContentFromPost(array(
            'slug' => $entryId,
        ));

        // Here I use elements->saveElement() because using entries->saveEntry
        // cased an infinite loop.
        // It would be great to have this sanity checked as well, please :)
        craft()->elements->saveElement($entry);
    });
}


texts: Adding alt text/title attributes to assets in a rich text field

texts:
I have custom fields for altText and title on some asset image locations.

Wondering if there is a good way to have those automatically added when a user puts in an image from a rich text field.


texts:
Leading on from this question by Chris Lewis

I can't seem to find anything on the technicals, but by what criteria "best-match to worst-match" calculated? For example, if I was to have, an entry with the title "Top Trees" then "Top Trees" I would expect to be a "best-match"?

This is a little bit "How do I get my post to the first page of the Craft Search!" I know.


texts:
When attempting to install Craft 3 in OSX El Cap, I'm getting the following errors:

  Script @php craft setup/welcome handling the post-create-project-cmd event returned with error code 255
  /Craft3/vendor/craftcms/cms/bootstrap/bootstrap.php on line 104

  Parse error: parse error in PATH/vendor/craftcms/cms/bootstrap/bootstrap.php on line 104
  Script @php craft setup/welcome handling the post-create-project-cmd event returned with error code 255

I used the --ignore-platform-reqs flag as I am using PHP7 on MAMP.

When I attempt to load index.php in the browser I'm seeing this seemingly related issue in the trace:

  in PATH/web/index.php at line 21 – yii\base\Application::run() 15161718192021    (new Dotenv\Dotenv(CRAFT_BASE_PATH))->load();}

  // Load and run Craft
  define('CRAFT_ENVIRONMENT', getenv('ENVIRONMENT') ?: 'production');
  $app = require CRAFT_VENDOR_PATH.'/craftcms/cms/bootstrap/web.php';
  $app->run();

I've substituted "PATH" in all errors in lieu of the actual path.

Any advice on resolving this would be much appreciated.


texts: How do I write an if statement to show Isotope filter button only if the Entry Section has content?

texts:
I'm creating an isotope filter and have the following code. Could someone please help me write an if statement showing the buttons only if any of these entries have content. For instance the CD button if statement would check if the Entry "album" type "cd" and Entry "single" type "cd".

{# Albums #}
{% set albumCd = entries.section('album').type('cd') %}
{% set albumVinyl = entries.section('album').type('vinyl') %}
{% set albumCassette = entries.section('album').type('cassette') %}
{% set albumOther = entries.section('album').type('other') %}

{# Singles #}
{% set singleCd = entries.section('single').type('cd') %}
{% set singleVinyl = entries.section('single').type('vinyl') %}
{% set singleCassette = entries.section('single').type('cassette') %}
{% set singleOther = entries.section('single').type('other') %}

{# Collectable #}
{% set otherVideo = entries.section('other').type('video') %}
{% set otherMagazine = entries.section('other').type('magazine') %}
{% set otherPrint = entries.section('other').type('print') %}
{% set otherCollectable = entries.section('other').type('collectable') %}

<button class="filt btn" type="button" data-filter="*">show all</button>
<button class="filt btn" type="button" data-filter=".CD">CD</button>
<button class="filt btn" type="button" data-filter=".Vinyl">Vinyl</button>
<button class="filt btn" type="button" data-filter=".Cassette">Cassette</button>
<button class="filt btn" type="button" data-filter=".Other">Other</button>
<button class="filt btn" type="button" data-filter=".Magazine">Magazine</button>
<button class="filt btn" type="button" data-filter=".Print">Print</button>
<button class="filt btn" type="button" data-filter=".Collectable">Collectable</button>


texts: How do I pass a URL segment to a search parameter?

texts:
I'm trying to set up an archive page by passing dates in the URL to the entries search parameter to show events from a specific month.  The eventstart is a custom date field.  If I enter numbers i.e. 2017-11 in the search parameter it works but the URL segments don't seem to parse.

Thanks in advance.

{% set year = craft.request.segment(3) %}
{% set month = craft.request.segment(4) %}

{% set entries = craft.entries.section('calendar').search('eventstart:"year-month)"') %}

{% for entry in entries %}

{{ entry.title }}

{% endfor %}


texts: How to Attach a User or Users to a Company

texts:
Ok, we have users and we have companies and we have different company locations. How to attach them? Or what's the best practice in attaching a user to a structure (company/location)? Or is there another way to approach this? Thanks!
John Doe -> abc-company
Jane Smith -> abc-company
Jacky Smith -> abc-company/location-a
Robert Craft -> xyz-company
Joe Craft -> xyz-company/location-south
Jane Doe -> xyz-company/location-north


texts: Redirect IE7 or below users to a new page

texts:
Traditional .htaccess or
<!--[if lt IE 7]><meta http-equiv="refresh" content="0; url=/assets/errors/ie.html"/><![endif]-->
methods don't work to redirect users in Craft.

I know it may seem taboo, but quite frankly I don't want anyone who is using IE7 or below to access my site. I'd like to completely redirect them to a separate page/template that will instruct them on why they can't see the site and how to upgrade.

Any ideas how best to achieve this?

Cheers, Mark.


texts: Relation fallback if no category has been selected

texts:
I have a filter with a few different parameters that get pulled in and I was wondering if there was a relatedTo wildcard that I could use.

Here's the relevant code:

{% set function = craft.app.request.getParam("function") %}

{% set functionSection = 'craft.categories.group('businessFunction')'  %}

{% if function | length %}
    {% set functionSection = craft.categories.group('businessFunction').slug( function|split(',') ) %}
{% endif %}

{% set posts = craft.entries({
          section: category,
          relatedTo: [
              'and',
              { element: functionSection }
          ]
}) %}

The problem is if an entry doesn't have any Business Function selected then it's not related. I could have a conditional that ignores the relationship but there's multiple relations in the real code - it'd be easier if I could set functionSelect equal "all" or something similar.


texts:
I've got an advanced search form which culminates in:

craft.entries.section('whatsOn').relatedTo(
    'and',
    { element: artCategories },
    { element: locationCategories },
    { element: bbfcCategories }
).search(searchTerm).order('score').limit(8)

This works, but only if the item being searched for has populated artCategories, locationCategories, and bbfcCategories.

Any of those are optional; i.e., the bbfcCategories line may not be needed at all... and likewise the searchTerm - is there a way to do this dynamically?


texts:
I have installed the latest version of Craft and I tried to open the Plugin Store.

I get the following message:

  Der Plug-in-Store ist nicht erreichbar. Bitte versuchen Sie es zu einem späteren Zeitpunkt erneut.

In English:

  Plugin Store is not available and I should try it later.

I have this problem for around 2 days now, since I installed the latest craft. Any advice?


texts:
I was wondering if there is a better way to do a query like this, it takes a long time to execute and I know setting the parent variable is where there's a problem but am not sure of an alternative way to do it. Appreciate any and all help!

{% set searchResults = craft.entries.section(['post']).search(searchQuery).with(['catalogue', 'postImage']).where({'field_show': 1}).limit(20) %}
{% paginate searchResults as pageInfo, pageEntries %}

  {% for item in pageEntries %}
        {% set image = item.postImage[0] ?? null %}
    {% set catalogue = item.catalogue[0] ?? null %}

              {{ item.title }}

    {% endfor %}

                {% if pageInfo.prevUrl %}Previous{% endif %}

                Showing page {{ pageInfo.currentPage }} of {{ pageInfo.totalPages }} pages

                {% if pageInfo.nextUrl %}Next{% endif %}

    {% for item in pageEntries %}
      {% set image = item.postImage[0] ?? null %}
      {% set catalogue = item.catalogue[0] ?? null %}
      {% set parent = craft.entries.section('parents').relatedTo({targetElement: catalogue, field: 'catalogue'}).one() %}

{{ item.title }}

{{ parent.title }}

{{ parent.date|date('l jS F Y') }} {{ parent.time and parent.archived != '1'  ? parent.time|time('g:iA') }}

    {% endfor %}


texts:
I have an issue where I cannot permanently delete a sub-folder from the "Assets" section in the control panel. When I delete the sub-folder, it does delete, however after logging out or a little time has passed, the folder reappears.
Is this a bug or is there a way to permanently delete the folder?


texts:
Good morning and thank you in advance. Very to new Craft and Twig so I am not sure if I am coding this correctly but need some help.

I have a forms center that has 5 main categories (Members, Finance, Technology, etc, etc)

On my members landing page, I only want to display forms that are associated to the members category then order those forms by sub categories.

I have got that working, but when I associate a form to another category (say Finance - OTL PALS), the OTL PALS sub category now shows on my members page.

Here is the associated entry image:

Here is my code... Not even sure if this is the correct way but it is working for the most part. I am pulling the slug (members) to get a list of form entries.

POPULAR FORMS

        {% set categories = craft.categories.group('formLocation') %}
        {% set projects = craft.entries.section('formCenter').relatedTo(craft.categories.slug(craft.app.request.segments|first)).orderby('title').limit(null) %}

                {% for category in categories.relatedTo(projects).all() %}
                    {% if category.level > 1 %}
                        {% set class = "" %}
                        {% if loop.index == 2 %}
                            {% set class = "current-active active" %}
                        {% endif %}

{{ category.title }}

                    {% endif %}
                {% endfor %}

            {% for category in categories.relatedTo(projects).all() %}
                {% if category.level > 1 %}
                    {% set class = "" %}
                    {% if loop.index == 2 %}
                        {% set class = "active" %}
                    {% endif %}

                                {% for entry in projects.relatedTo(category).all() %}
                                    {% set file = entry.forms.one() %}
                                    {% if file|length %}

{{ entry.title }}

                                    {% endif %}
                                {% endfor %}

                {% endif %}
            {% endfor %}


texts: How to manage different templates for a structure

texts:
i am trying to figure out the right way to display elements on a page.
Its about a website for a fashion designer. There will be parent elements like :

Parent X
Parent Y

both of those elements use the same template and i used structure for it. i figured structure is the right choice because of the ability to sort them in the panel etc.

It should be possible to add child elements to the parents like

Parent X

Item a
Item b

Parent Y

Item c

etc..

those elements are using a different template:

Like
- ParentTemplate/

and
- ParentTemplate/ItemTemplate/

how can i structure them in the craft panel without making them a new structure, because the new structure isnt related to parents then anymore , what they have to be ... ot is it the wrong approach here ?

thanks a lot guys


texts: 1 free shipping item in cart, minimum shipping fee still applied

texts:
I understand why it is happening, but I'd like some help figuring a way around it. I suppose its probably a plugin.

I'm using weight based shipping calculations and its all fine. Except when I have a product using the free shipping field. I have a min shipping charge of $15, and that still gets applied even though there is 1 product in the cart and it has free shipping checked.

I need to be able to iterate over all cart items, and if all of them have free shipping checked, to zero out the shipping charge, or, effectively, circomvent the minimum shipping fee setting.


texts: How to get rendered image paths from the ElementAPI?

texts:
I'm wanting to return HTML content via the ElementAPI. I seem to be able to do this with the following elements.php:

'endpoints' => [
    'api/trials.json' => [
        'elementType' => 'Entry',
        'criteria' => ['section' => 'trials'],
        'transformer' => function(EntryModel $entry) {
            return [
                'summary' => ($entry->summary ? $entry->summary->getRawContent() : false),
                ...
            ];
        },
    ]
]

It's just that the getRawContent() returns the following in the JSON:

"summary": "
<img src=\"{asset:46:url}\"…

When I'm expecting:

"summary": "
<img src=\"/images/myimage.png"…

Should I be using a different method to get to the content, or do I need to run the content through some kind of transformation?

Thanks in advance,

James


texts: Query Entries based on current Entry's related Entries

texts:
I'm wanting to show related articles based on the current article's related Markets.

How do I get the current markets and filter relevant posts based on those related markets? This is what I have so far but doesn't seem correct.

{% set allMarkets = entry.relatedMarkets.all() %}
{% set currentID = entry.id %}

{# Get Related Articles Based on Markets #}
{% set expertBlog = craft.entries()
    .section('blog')
    .orderBy('postDate desc')
    .expertOpinion(true)
    .relatedMarkets([allMarkets])
    .id(['not', currentID])
    .limit(3) %}

Enjoyed this article? Keep reading more expert insights...

          {% cache %}
          {% for entry in expertBlog %}
              {% set columns = 'w-100 w-50-m w-33-l w-33-xl' %}
              {% include "_partials/lists/blog/_cards_blog_article_authors_expert.twig" %}
          {% endfor %}
          {% endcache %}


texts: Filters using multiple query strings with pagination and Craft Commerce

texts:
I want to build the ability for the user to be able to filter by certain categories when browsing an existing category. As well as this I would like the user to be able to control the ordering of products (order by price, title, sale) and perhaps (tbc) the ability to choose how many products are shown. Finally, some products depending on the limit will have pagination for both the unfiltered results but also the filtered results.

The filters currently are brand and life-stage but there could be others depending on the growth of the site.

I do have these all working with Craft in isolation I am really unsure of the best way to pull these together so that they all work in harmony. Currently if you filter on a brand and then change the order the brand is lost and goes back to the main category view. This is because I am using query-strings to filter the brands, life-stage, ordering and limit.

Any thoughts on the best way to tackle this from a front-end approach and also templating approach?

I should perhaps add that the ability to filter by categories (brands etc) sits in a different location to the order function. So this might make things slightly more tricky as perhaps form could work to accomplish this?

Thanks


texts:
If I set say NZD as the primary currency now and then change to USD or EUR down the track will I have to re-price the products or will they pick up the converted pricing?

I'm planning on having USD, AUD, NZD, EUR, GBP and using the Currency Layer plugin for live conversion rates.


texts: How can I display just the "lowest" categories assigned to an entry and not parent categories?

texts:
I have a category tree like this and I have an entry that has four categories A, A1, B, C2:

A

A1
A2

B

B1
B2

C

C1
C2

I want a query that ignores A and returns only A1, B, C2, because I don't want to display the parent category of a sub-category that's also displayed.

{% for category in entry.businessTypes.all() %}{{ category.title }}{% endfor %}
returns all: A, A1, B, C2

{% for category in entry.businessTypes.leaves().all() %}{{ category.title }}{% endfor %}
returns A2, C2 but not B.

{% for category in entry.businessTypes.hasDescendants().all() %}{{ category.title }}{% endfor %}
returns A, B but not A1, C2.

Any suggestions are appreciated.


texts: Escaping characters in entry.postDate|date

texts: {{ entry.postDate|date('jS F Y \at ga') }}This should produce this 5th November 2016 at 4ambut it doesn't seem to recognise the escape and adds 30 instead of at.


texts: How can I get to a category via the category slug using the ElementAPI

texts:
I am using the ElementAPI to generate a json response of data based on the value (locations) that was chosen from a drop-down.

I think I have all of the pieces I need, i'm struggling with how to put them all together I think.

twig

{% set locations = craft.categories.group('locations') %}
...
{% for location in locations %}
    <option value="{{ location.slug }}">{{ location.title }}</option>
{% endfor %}

elementapi.php

$slug = craft()->request->getRequiredPost('location');  // chicago
$category = craft()->categories->getGroupByHandle('Locations'); // category group
$location = ??

return [
    'endpoints' => [
        'myfile.json' => [
            'elementType' => 'Entry',
            'criteria' => [
                'section' => 'mysection',
                'relatedTo' => ['targetElement' => $location],
            ],
            'transformer' => function (EntryModel $entry) {
                return [
                    'title' => $entry->title
                ];
            },
        ]
    ]
];


texts: Plugin Settings UI for saving an array of values

texts:
I'm making a plugin where I'd like a user to be able to add values to a list, then have that list saved as an array.  Are there any smart ways of doing this? My current solution is to have a textarea, then make values out of each line but that's not ideal at all. Does Craft already have a built-in UI pattern for this?

Thank you!


texts:
I have the following code in the “main.twig” template:

<head>
    {% block head %}
        <meta property="og:image" content="{% block pageImage %}{% endblock %}" />
    {% endblock %}
</head>

Then, I’m trying to populate the image URL into the < meta > tag from a Matrix field:

{% extends "templates/main" %}
{% for block in entry.articleBody %}
    {% if block.type == "articleImage" %}
        {% set image = block.articleImage.first().getUrl() %}
        {% block pageImage %}{{ image }}{% endblock %}
    {% endif %}
{% endfor %}
{% block head %}{{ parent() }}{% endblock %}

However, no URL is outputted. Does anyone know why?

Thanks!


texts: exclude list of entries from craft.entries tag

texts:
I am attempting to list out all jobs that the current author has created but which are not already to other entries they've created.

I have both an array and a string containing the entry ids to exclude which I can see with these tags:

{# delete later, only here to visually show entry ids while coding #}

array: {{ excludeRelatedJobs|join(', ') }}

{# convert array to string #}
{% set excludedJobs = excludeRelatedJobs|join(', ') %}

string: {{ excludedJobs }}

However when I try to exclude the ids from the list they are not excluded.

current code that should exclude ids:

{% set careers = craft.entries.section('careers').authorId(user.id).id('not' ~ excludedJobs) %}

    {% for job in careers %}

{{ job.title }}

    {% endfor %}

If I manually exclude the id like this it works correctly:

{% set careers = craft.entries.section('careers').authorId(user.id).id('not 581') %}


texts:
Wondering if I can get user groups directly after retrieving the user via craft()->users->getUserById($id), or if i need to use craft()->userGroups->getGroupsByUserId($id) also?

As of right now, I'm looping through many users and want to check if they are in a specific group. A rough idea of what I'm looking at now:

// get user (necessary for rest of plugin)
$user = craft()->users->getUserById( $uid );

// get user groups
$user_groups = craft()->userGroups->getGroupsByUserId( $uid );

// check if user is in group
if( in_array("Group_Name", $user_groups) )
{
   // do something
}

This works, but when looping through a ton of users, I imagine it would be silly not to first check that I can already get this information from the $user variable I created. I can't seem to find the answer via documentation. Hoping to get a confirmation from someone!

Thanks


texts:
In PHP, is it possible to grab the customer model from a user model?

EDIT:
I just noticed that it is possible to attach a customer info field to the user.  How do we achieve this?


texts:
Is there anything with craft like Laravel's Form Requests?

I am writing a plugin with a custom entry type. Right now, I am doing the store/edit pages and I do not want to reinvent the wheel ;)

Is there any way in craft/yii to easily validate the submitted values from a post request? Or what is the best practice in this case for craft?


texts: Setting cookies from CTA before directing to url?

texts: I need to set some cookies based on some CTA button links. I will later be checking for these cookies to determine what content to display on the entry with the cta on the next visit and other entries etc. Seems like I would need to set the cookie via javascript on click event and then direct them to the url they clicked, anyone know of a way to do this without javascript and have an event handler for the cta clicks?


texts: Update fails: mod_fcgid: read data timeout

texts:
I keep getting the following error when trying to update my craft installation.

mod_fcgid: read data timeout in 31 seconds, referer: https://mysite.com/admin/manualupdate/craft
End of script output before headers: index.php, referer: https://mysite.com/admin/manualupdate/craft

I have tried updating my /etc/apache2/mods-available/fcgid.conf file with:

FcgidConnectTimeout 600
FcgidIOTimeout 600
IdleTimeout 600
ProcessLifeTime 600
IPCConnectTimeout 600
BusyTimeout 600

And this has given no results. I still get the error. The database wasn't able to go rollback and the site is currently not available. Unfortunately this is happening in production...

Help?


texts: Fields applied to the User area are not translatable?

texts:
I have a site which allows people to register as a member from the front end. I've got a bunch of fields attached to the User so that each person can build their own extended profile page; the site is bilingual. I've successfully got fields translatable when they're attached to a Section (the fields are marked as translatable), but when the same fields are attached to User there appears to be no way to input content in a different language; the familiar language switch in the back-end is not there... what am I missing?

E.g., here is the biography field, marked as translatable:

Here is the result when the field is used in a Section (note the interface has a language switch on the right, which can be toggled and the contents of the biography field changes):

But here is the same field when used in a User, note the lack of a way to change the language:

Bonus Question:
Assuming these fields are translatable; how would I get the front-end user form to list the fields in both English and Welsh so the user could fill in both on one page (i.e., without them needing to switch the site itself into another language)?


texts:
Craft CMS V2.
Comment Plugin: verbb comment

    {% nav comment in comments %}
       {% if comment.isFlagged() == false %}

              {% include '_forms/templates/comment-' ~ comment.status %}
              {% include '_forms/templates/form' %}

            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

       {% endif %}
    {% endnav %}

The above code creates this error:

Unexpected "ifchildren" tag (expecting closing tag for the "if" tag)

So, How can I use if/else condition inside the nav tag to hide flagged comment including it's children.


texts: Matrix entries field prevents following Matrix field to display

texts:
I've setup a Matrix field with an entries field and output the value like this:

{% set entry = block.blockLink.first() %}
 {% if entry %}

Find out more

 {% endif %}

This outputs the value of the entries field OK. However any other Matrix field that follows on from this one fails to display at all. What am I doing wrong? Any advice gratefully received!


texts: Guest Entries plugin will only submit when logged in - not anonymously (via AJAX)

texts:
I am trying to create an entry in a section via AJAX from the front end when not logged in. I am using the 'Guest Entries' plug in for craft to do this.

The entries are all the same and consist of only a title.

I have the whole thing working perfectly when I am logged in but not when I am logged out.

There is no form on the page as the whole thing is called via JS. The Jquery code looks like this:

var formData = [{name: "CRAFT_CSRF_TOKEN", value: "biglongtokenhere"},{name: "action", value: "guestEntries/saveEntry"},{name: "sectionId", value: "5"},{name: "title", value: "Added"}];
  $.post('/', formData , function(response) {
    if (response.success) {
      //do stuff
    }else{
      // do other stuff
    }
  });

When logged out all I get back is a 400 bad request error. Logged in as an admin it works perfectly.

The plug in is installed correctly and has a default author selected and the 'Entries Enabled by Default' slider set to true on the settings screen.

My understanding is the plugin should allow for anonymous entry submission. Thanks in advance for any suggestions.


texts: Is it possible to create a Craft boilerplate out of a project.yaml file?

texts:
I have setup a boilerplate for Craft sites with a homepage Single setup, plugins installed, common field types setup and a few other jobs I have to do every single time I start a new project.

I was wondering if this is something I can safely turn into a CraftCMS boilerplate?

In an ideal world it's something I'd keep in Git and when I start a new project in 3 months time or whatever it may be, I can copy this project.yaml into my new project and I'm an hour or so ahead of where I would be.

I know technically I probably could, but I'd like some advice on whether this is something I should or should not be doing.

Cheers


texts:
In my routes file I have this:

'micros-test/guest-booking/(?P<bookingId>[a-z0-9-]*)' => 'micros-test/guest-booking',

Which works fine for URLS like this:

  /en/micros-test/guest-booking/some-valid-alphanumeric-id

However I need to add another that I can't get working, this time with a querystring value, such as this:

  /en/micros-test/guest-reset-password?token=some-valid-alphanumeric-id

How can I get that to route to my endpoint and pass on the token parameter?

I've tried this but to no avail:

'micros-test/guest-reset-password/?token=(?P<token>[a-z0-9-]*)' => 'micros-test/guest-reset-password',

What have I got wrong there?


texts: Save Entry Data as CSV and Email it to the Author / Logged in User

texts:
I am trying to email some Entry data that they have created in CSV Format to the author/logged in user. I have a controller setup with a frontend form posting an action to the controller:

public function actionSendCSV(){
 $this->requirePostRequest();

 $entryId = craft()->request->getParam('entryId');
 $entry = craft()->elements->getElementById($entryId);

 $user = craft()->userSession->getUser();

 if ($user->id != $entry->getAuthor()->id) {
     HeaderHelper::setHeader(array('status' => 404));
     craft()->end();
 }else{
   $list = array(
     //This is test data I'll construct the entry data here
    "Peter,Griffin,Oslo,Norway",
    "Glenn,Quagmire,Oslo,Norway");
    $file = fopen("test.csv","w");
    foreach ($list as $line){
      fputcsv($file,explode(',',$line));
    }

    $email = new EmailModel();
    $email->toEmail = $user->email;
    $email->subject = 'Your CSV';
    $email->body = 'How you doin, {{ user.name }}?';

    // Im not really sure what to do next here - do I save the CSV as an asset and then link it here?
    $email->addAttachment('path/to/csv/', 'name in e-mail.csv', 'base64', 'text/csv');

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

Is this the best way to handle this or should I save the entry data as CSV to my assets folder(Perhaps create a folder just for that user in the process to store all exports from them?) and send a link to users? If so what is the best method to achieve this?

Thanks!


texts: How to fetch entries from multiple sections

texts:
I have five separate sections with x number of entries each. I would like to render all the entries from all the sections on a single entry template page. Is there a way to do this ? I know we can set entries like this  {% set entries = craft.entries.section('sectionHandle').limit(10) %} , but I'm not sure how to get entries from all the sections.

Any help or suggestion is highly appreciated.

Thanks!


texts: Order entries by custom date and time fields

texts:
I have an events channel where each entry has three custom date/time fields:

startDate (Date Only)

startTime (Time Only)

endTime (Time Only)

I was originally using this code to set my entries, but it causes problems if they aren't all entered on the same day:

{% set allEntries = craft.entries.section('sparkSchedule').limit(null).orderBy('startDate asc').all() %}

I've seen answers from Craft 2 saying that i could use time(startTime) to sort by just the time portion of my startTime field:

{% set allEntries = craft.entries.section('sparkSchedule').limit(null).orderBy('startDate asc, time(startTime)').all() %}

but when I do that, i get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'startTime' in 'order clause'

Am I doing something wrong?


texts:
I don't understand how Craft CMS processes cache with Redis especially when saving to database/s?
My environment:

Craft Pro 3.4.8
PostgreSQL 12.2
PHP-FPM 7.4.3
Redis 5.0.7

I followed examples from the Application Configuration documentation and It seems that Craft CMS works well Redis. From inspecting both databases, sessions and queue work as expected.

queue table is created in SQL DB but empty because all queue related storage is moved to Redis where I can see all the keys queue.message_id, queue.messages and queue.waiting. queue table will probably always stay in SQL DB from installation process.
when a session begins token value is created in sessions table in SQL DB with some session related attributes and I also could locate the same token key-value in Redis DB with additional info about current session. When session ended token was removed from both databases.

Cache
I created some matrix field content and I cached it.
I found out that a row with cacheKey and other attributes (along with body column) are created in templatecaches table in SQL DB.
Since using Redis I expected that all/most of cache related storage will be stored in Redis. Inspecting Redis and I couldn't find anything to cache related stuff.


texts: Global override specific field templates in Sprout Forms Plugin

texts:
I want to restructure the output of the way Sprout Forms generates checkboxes and radio buttons from that of the input.html in templates/_components. I need the label to appear after the radio/checkbox input for styling/accessibility purposes.

But I'm not seeing the documentation to override  without editing the plugin (obviously not a sustainable plan). Can I just put them in the designated Global custom form templates folder and have SproutForms look for form_overrides/radiobutton/input.html first?

Example of what I need to do:

<input type="radio"
  {%- if id %} id="{{ id }}-{{ loop.index }}"{% endif %}
  {%- if name %} name="{{ name }}"{% endif %}
  {%- if value %} value="{{ value }}"{% endif %}
  {%- if checked is defined and checked %} checked{% endif %}
  {{- required -}}
  {{- dataAttributes|raw -}}
>
    <label {%- if id %} for="{{ id }}-{{ loop.index }}"{% endif %}>
        {%- if label is defined %}{{ label|raw }}{% endif -%}
    </label>


texts: Can I use translated properties for URL formats

texts:
Here's my scenario.

I have a structure section: "events". Within that I have three entry types: "events", "exhibitions", "specials".

I would like the events to follow the following URL structure:

{type}/{slug}

So far no problem, since the entry type handles are defined in English. But when it comes to the Norwegian page, I want to use the Norwegian translation for each type: "arrangement", "utstilinger", "spesielle".

So I added in the translations to my static translation file, and tried:

{type|translate}/{slug}

But obviously, since I'm here, I didn't have any luck. Can anyone think of a way to achieve the desired result, without resorting to adding a custom field to each entry type that would need to be filled in for every entry to use in place of {type}?


texts: Why is my Super Table field returning the ID for existing blocks?

texts:
I have a front-end profile form that is using a Super Table field to populate a user's phone number.

If the user has not populated the field before, everything works great. I am able to use new1 to collect the user's information.

It is when I am trying to display existing data that I am getting the error

  Impossible to access an attribute ("id") on a string variable ("92").

I am following this guide to help show existing data.

This is what my template looks like:

{% set fieldHandle = 'phoneNumber' %}
{% set field = craft.fields.getFieldByHandle(fieldHandle) %}
{% set blocktype = craft.superTable.getSuperTableBlocks(field.id)[0] %}

<input type="hidden" name="fields[{{ fieldHandle }}]" value="">

<label for="phoneNumber">Phone Number</label>

{% if currentUser.phoneNumber.phoneNumber|length %}
    {% for block in currentUser[fieldHandle] %}
        <input type="hidden" name="fields[{{ fieldHandle }}][{{ block.id }}][type]" value="{{ blocktype }}">
        <input type="hidden" name="fields[{{ fieldHandle }}][{{ block.id }}][enabled]" value="1">

        <input type="text" name="fields[{{ fieldHandle }}][{{ block.id }}][fields][phoneNumber]" value="{{ block.phoneNumber.phoneNumber }}">
    {% endfor %}
{% else %}
    <input type="hidden" name="fields[{{ fieldHandle }}][new1][type]" value="{{ blocktype }}">
    <input type="hidden" name="fields[{{ fieldHandle }}][new1][enabled]" value="1">

    <input type="text" name="fields[{{ fieldHandle }}][new1][fields][phoneNumber]"
    {%- if currentUser is defined and currentUser.phoneNumber.phoneNumber|length -%}value="{{ currentUser.phoneNumber.phoneNumber }}"{%- endif -%}>
{% endif %}

While trying to debug myself, this:

{{ currentUser[fieldHandle] }} // 92

So this:

{% for block in currentUser[fieldHandle] %}

...is really saying "for block in 92". So, that is why I am getting the error, I'm not sure what the correct syntax is to resolve the error though.

My super table is set to have a max rows of 1 and static field is selected.

Thank you for any suggestions!


texts: How can I update a custom Order field in a plugin controller?

texts:
I have a custom plugin in which I have a controller action which I want to validate some values and then update a custom field on the Cart.

I can get the values from the form and validate them, I'm just missing how to get them saved to the Cart.

I've tried the following:

$this->cart->setRawPostContent('orderShippingOptions', $myValue);
$this->cart->setContentFromPost('fields');

And also just:

$this->cart->setContentFromPost(['orderShippingOptions' => $myValue]);

I'm feel like I'm in the right area, I'm just missing something simple.

Any help gratefully received.


texts: Custom event not sending notification email

texts:
I'm creating a plugin called "Membership" to handle user subscriptions through Stripe. I want to use SproutEmail to handle notification.

I've created a custom event as per the Sprout instructions:

<?php
namespace Craft;

class SproutEmail_SubscribeEvent extends SproutEmailBaseEvent
{
    /**
     * Returns the qualified event name to use when registering with craft()->on
     *
     * @return string
     */
    public function getName()
    {
        return 'membership.onSubscribe';
    }

    /**
     * Returns the event title to use when displaying a label or similar use case
     *
     * @return string
     */
    public function getTitle()
    {
        return Craft::t('When a user subscribes to a membership plan.');
    }

    /**
     * Returns a short description of this event
     *
     * @return string
     */
    public function getDescription()
    {
        return Craft::t('Triggers after a user has subscribed.');
    }

    /**
     * Returns the data passed in by the triggered event
     *
     * @param Event $event
     *
     * @return mixed
     */
    public function prepareParams(Event $event)
    {
        return [
            'value' => $event->params['user']
        ];
    }
}

SproutEmail is picking this up and I can select it as a rule:

I added a listener to my plugin for membership.onSubscribe to ensure it's working properly:

craft()->on('membership.onSubscribe', function(Event $event) {
    MembershipPlugin::log('membership.onSubscribe was triggered.');
});

And it appears to be:

2017/02/16 15:07:33 [info] [plugin] membership.onSubscribe was triggered.
in /home/vagrant/Code/sbl.loc/craft/app/etc/plugins/BasePlugin.php (65)
in /home/vagrant/Code/sbl.loc/craft/plugins/membership/MembershipPlugin.php (56)
in /home/vagrant/Code/sbl.loc/craft/plugins/membership/services/MembershipService.php (15)

******************************************************************************************************

However SproutEmail doesn't sent out any notification email and when I check the logs for the plugin there is no mention that my custom event was triggered.

Does anyone have any idea what the issue might be?


texts: Search Plus - How to skip an entry in mapping?

texts:
With the Search Plus plugin, it's possible to define a custom mapping of your Entries for your Algolia index. This is basically a two-part process:

Call the searchPlus_addAlgoliaMapping to declare which function controls the mapping.
Write the function which controls the mapping.

I've done both of these, and it's working very well. Here's an example of my mapping function...

return [
    'objectID' => $entry->id,
    'uri'      => $entry->uri,
    'title'    => $entry->title,
];

However, there are certain entries which should be excluded from the search index. My instinct tells me to simply wrap a conditional around that mapping, and return false (or null) for entries which should be excluded...

if ($entry->includeInSearch) {
    return [
        'objectID' => $entry->id,
        'uri'      => $entry->uri,
        'title'    => $entry->title,
    ];
} else {
    return false;
}

The problem is, this seems to cause an error when Search Plus tries to export to Algolia...

Which leads to the question: What is the proper way to omit an entry from an Algolia index?


texts: Freeform - using multiple fields on the same form

texts:
I have a set of very long forms.  Many of these forms require repetitive field types - example:  one of my forms requires the "date" field 15 times.

Another form requires at least 30 single line text entries + dozens of radio button entries.

It appears I can only use a field once per form, forcing me to create a new field each time I use a previous one.  Is there any way around this?

I see I can re-label fields for each form which helps but wondering if there is a better way.

I'm definitely going to run up against the 130 field limit if I have to create new ones each time.


texts:
I want to modify this query so that the dated entries are sorted in descending order on a custom field called 'startDate'.

Have tried adding .order('startDate') to the end of the craft.entries(query)... but this causes any entry with a startDate to be excluded from the query.

(Maybe it's possible to set the order on just the {% for entry in programmeEntriesDated... loop?)

{% set query = { section: 'programme' } %}
{% set query = category is defined ? query | merge({ relatedTo: category }) : query %}
{% set programmeEntriesDated = craft.entries(query) %}

{# Show programme entries if available #}
{% if programmeEntriesDated|length %}
<div class="flex flex-wrap flex-row-ns">
  {# DATED ENTRIES #}
  {% for entry in programmeEntriesDated if (
        (entry.startDate|date('Y-m-d') >= now|date('Y-m-d'))
    or  (entry.endDate is not null and entry.endDate|date('Y-m-d') >= now|date('Y-m-d'))
    ) and
        (entry.type != 'old_programme_entry')
    and (entry.isOngoing == 0)
  %}
    {% include "_blocks/event_single.html" with { 'blockWidth' : 'w-100 w-third-ns' } %}
  {% endfor %}

  {# ONGOING ENTRIES  #}
  {% for entry in programmeEntriesDated if (entry.isOngoing) and
        (entry.type != 'old_programme_entry')
  %}
    {% include "_blocks/event_single.html" with { 'blockWidth' : 'w-100 w-third-ns' } %}
  {% endfor %}
</div>


texts:
When I try to initiate tasks on uninstall the tasks fail because the plugin completes uninstalling before the tasks. The task is referencing an uninstalled plugin at that point. Once the plugin is uninstalled I get this error:

Encountered an error running task 23 (xxxx): Could not find the task component type.

Which makes sense. However, uninstall takes a long time because there are many things needing clean up so is there any way I can have tasks continue to work after the plugin is uninstalled?


texts: How to deploy website from dev to staging from localhost to remote server using composer

texts:
I want to upload all my Craft files along with the database to an Ubuntu server using composer. This server is an EC2 instance of AWS.

Thanks for the help!


texts: Multiple Images/Assets from Super Table?

texts:
I have a Super Table "previewImage" with a field "previewImageFile".

This does not work:

  {% for subsection in entry.descendants.descendantDist(1).all() %}

{{ subsection.shortTitle }}

      {% set image = subsection.previewImage.previewImageFile.one() %}
      {% if subsection.previewImage.previewImageType.value == 'jpg' %}
      {% set transformedImages = craft.imager.transformImage(image,
        [
          { height: 250, jpegQuality: 90 }
        ],
          {
            format: 'jpg',
            allowUpscale: false,
            resizeFilter: 'lanczos',
            effects: { unsharpMask: [0, 0.55, 0.55, 0.008] },
            interlace: false,
            convertToRGB: true
          }
      ) %}

      {% else %}

      {% set transformedImages = craft.imager.transformImage(image,
        [
          { height: 250 }
        ],
          {
            format: 'png',
            allowUpscale: false,
            resizeFilter: 'lanczos',
            effects: { unsharpMask: [0, 0.55, 0.55, 0.008] },
            interlace: false,
            convertToRGB: true
          }
      ) %}
      {% endif %}

      {% for image in subsection.previewImageFile %}

        <picture>
          <source class="img-fluid" srcset="{{ craft.imager.srcset(transformedImages) }}" type="image/jpeg">

        </picture>
        {% endfor %}

    {% endfor %}

I get the a (link) without images.

I guess previewImageFile.one() is wrong.
But setting it to all throws a error:

get_class() expects parameter 1 to be object, array given


texts: How do you replicate the EE {date_heading} tag pair in Craft?

texts:
I'm wondering how I would replicate the ExpressionEngine date_heading tag pair in Craft?

{date_heading}  {entry_date format="%Y %m %d"}  {/date_heading}

  The date heading can be used to show a heading at certain intervals.
  The interval can be set to show hourly, daily, weekly, monthly, or
  yearly.


texts:
I'm trying to return entries based on some criteria. I exclude entries with a given value like this:

{% set someEntries = craft.entries({
    level: 1,
    id: '1,2,3,4,5',
    myOtherField: 'not blue'
}) %}

But it doesn't work if I try to exclude by multiple values:

{% set someEntries = craft.entries({
    level: 1,
    id: '1,2,3,4,5',
    myOtherField: 'not blue and not green'
}) %}

It's not in the docs and I've tried a few different syntax but had no luck.


texts: Feed Me - feed format for importing into Super Table field

texts:
I am trying to import a list with the following format in each list item:
<Date> - <Title> - <Icon> - <External Link>
into a Super Table block containing fields for each of the above.

I tried with different xml formats following the documentation, but did not have any success importing multiple rows in the same Super Table field.

I wish to have it as:

SuperTable field:

<Date> - <Title> - <Icon> - <External Link>
<Date> - <Title> - <Icon> - <External Link>
<Date> - <Title> - <Icon> - <External Link>

But it creates a new Super Table entry with just a single row for the new list item each time.

i.e.

SuperTable field:

<Date> - <Title> - <Icon> - <External Link>

SuperTable field:

<Date> - <Title> - <Icon> - <External Link>

SuperTable field:

<Date> - <Title> - <Icon> - <External Link>

My current xml format is:

<entries>
  <entry>
    <SuperTable>
      <Row>
        <date><![CDATA[1583366400]]></date>
        <content><![CDATA[Some text here]]></content>
        <icon><![CDATA[]]></icon>
        <link><![CDATA[https://www.google.com]]></link>

      </Row>

      <Row>
        <date><![CDATA[1557273600]]></date>
        <content><![CDATA[Some more text for second item]]></content>
        <icon><![CDATA[]]></icon>
        <link><![CDATA[https://www.facebook.com]]></link>
      </Row>
    </SuperTable>
  </entry>
</entries>

Anyone could please point me to the right direction?


texts: Use function provided by plugin only if plugin is installed and enabled

texts:
I want to use asset rev in my template, but only if plugin is installed and enabled:

    {% if craft.app.plugins.getPlugin('assetrev') is not null and craft.app.plugins.getPlugin('assetrev').isInstalled %}
        {% set fileName = rev(file) %}
    {% else %}
        {% set fileName = file %}
    {% endif %}

Hovewer when i disable plugin, mere existence of rev function in my template, still causes error.


texts:
After recently discovering the logs for Sprout forms (located in craft/storage/runtime/logs) I have been studying them and debugging new forms that I am creating.

After integrating a form hook in my templates, I am getting an error: A form submission failed because the user did not have Javascript enabled. - but I do have Javascript enabled... it is prevalent on other parts of the page.

Any tips... ?


texts:
I need to be able to output the price of a subscription after the user has subscribed. I'm using the Stripe Gateway. This post indicates to use {{ subscriptionPlanData.plan.amount }} but that doesn't seem to work for Commerce 3.
Commerce 2 Subscription Prices
The code below works but only after you refresh the payment history for the subscription in the admin, which seems to be a manual task.
{% set payments = subscription.getAllPayments() %}
      {% if payments %}
           {% for payment in payments %}
                ${{ payment.paymentAmount|number_format(2, '.', ',') }}
           {% endfor %}
      {% endif %}

Any idea how to get that payment history to automatically refresh after a subscription? Since that includes taxes, etc. that might be the best solution?


texts: Use an entry field's value in body class

texts:
I have created a plain text field that is assigned to a section and is available in the tabs for entries in that section. I want to use this field's value to modify the CSS on my template. My _entry.html file looks like the following:

{% extends "_layouts/site" %}
{% set title = entry.title %}
{% set modifierClass = entry.shortName %}
{% set bodyClass = "work modifierClass" %}

{% block main %}

{% endblock %}

I have assigned the entry.shortName to the customClass variable, but it is not working correctly. The text "modifierClass" is outputted in the body tag instead of what is entered in the entry.shortName field. If I place the {{ entry.shortName }} within the
 tags, it is outputted correctly there.

Any reason why this is not working? Or am I not understanding how field values can be assigned to variables.

Cheers,


texts: Geo plugin returns Undefined property: stdClass::$traits

texts:
I'm using Luke Holder's Geo plugin and it's been working great, so far. I'm testing on mobile and while it works fine on my Android device, visiting the site on two different iPhone 6s has resulted in the following error:

Internal Server Error
Undefined property: stdClass::$traits

Line 94 in https://github.com/lukeholder/craft-geo/blob/master/geo/services/Geo_LocationService.php is responsible but I haven't yet figured out why it's doing it, nor how to prevent it.

Both phones are on a different mobile network (O2 in the UK) to my Android device (Three). I've tested on an iPhone SE (Tesco, which piggy-backs O2) and that's fine. So it's either the iPhone 6 that's the problem, or their network. But manually entering the Nekudo URL with the IP addresses reveals nothing different.

http://geoip.nekudo.com/api/92.10.112.255/full (IP of Android device)

http://geoip.nekudo.com/api/82.132.243.85/full (IP of one of the iPhone 6s)

The site is not in devMode (everything is fine when it is). I can't understand why the same server would return a server error for one phone and not another phone. There was an issue with the plugin returning this error when using a local IP address but I don't think that applies here. I ahve noticed that the two phones in question are locating to London, 100 miles away from their true location - could that be a clue?

Any ideas?


texts:
I'd like to set the screen_name for a list of tweets using Dukt Twitter.

The screen_name is set in an entry as a plain text field.

{% set entries = craft.entries.section('contactPage') %}
{% for entry in entries %}
{% if entry.twitterHandle|length %}
{% set tweets = craft.twitter.get("statuses/user_timeline.json?screen_name='~ entry.twitterHandle ~'&count=3") %}
    {% if tweets %}

Recent Tweets

    {% for tweet in tweets %}

{{ tweet.text|autoLinkTweet }}

{{ tweet.created_at|date('M j Y') }}

    {% endfor %}

    {% else %}

Recent Tweets

No recent tweets at this time.

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

Not possible? No matter what I try, I only get the feed for the oauth user. Any help would be greatly appreciated!

Thanks!


texts: Using element API to query a matrix field

texts:
I'm using the Element API to grab entries and their data (via this answer). What I want to do is accept a URL parameter (eg. ?location=foo) and filter the returned entries by a Matrix field called fundingProgramme, where its sub-field area (a dropdown) has a value matching the URL query parameter.

I can't work out how to do this using the Element API. Here's what I've got:

'content/<locale:en|cy>/programs.json' => function($locale) {

    $siteId = ($locale === 'en' || !$locale) ? 1 : 2;

    return [
        'elementType' => Entry::class,
        'criteria' => [
            'section' => 'fundingProgrammes',
            'siteId' => $siteId
        ],
        'transformer' => function(Entry $entry) {
            $request = Craft::$app->getRequest();
            $location = $request->getParam('location');
            return [
                'title' => $entry->title,
                'test' => $entry->fundingProgramme[0]->area->label
            ];
        },
    ];

(the test key at the end is me proving that I can retrieve the field programmeTitle from the Matrix field fundingProgramme. There's only one stored against each entry, though).

How can I query against this field? Would I have to do this in the transformer rather than the criteria?


texts: Smart Map - Setting single map with multiple pins

texts:
I have a Smart Map field in a section and am trying to output multiple results (pins) to a single map.
This code will output multiple maps (one map per pin)
{% for mapEntry in craft.entries.section('markets') %}
{% set options = {
    height: 500,
    zoom: 14,
    draggable: false,
    markerInfo: '_includes/mapInfoBubble',
    markerOptions: {
        icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
    },
    infoWindowOptions: {
        maxWidth: 200
    }
} %}

{% set locations = craft.entries.section('markets').marketAddress.find() %}

{{ craft.smartMap.map(locations, options) }}

{% endfor %}

So essentially I am trying to get the {{ craft.smartMap.map(locations, options) }} outside the for loop.
{% set locations = '' %}
{% set options = '' %}
{% for mapEntry in craft.entries.section('markets') %}
{% set options = {
    height: 500,
    zoom: 14,
    draggable: false,
    markerInfo: '_includes/mapInfoBubble',
    markerOptions: {
        icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
    },
    infoWindowOptions: {
        maxWidth: 200
    }
} %}
{% set locations = craft.entries.section('markets').marketAddress.find() %}
{{ craft.smartMap.map(locations, options) }}
{% endfor %}

But this only results in a single pin (most recent entry).
Can't get my head around this. Any assistance most welcome.


texts:
I'm working on a site that I did not build.

The first party contact form stopped submitting so I updated Craft and all plugins. All went smoothly but the form is still not  submitting.

Checked the templates and compared to the docs and it appears that it should work (was previously). Any recommendations on how to better troubleshoot?

  {% from _self import errorList %}

  <form id="contact-form" method="post" action="" accept-charset="UTF-8" enctype="multipart/form-data">
      {{ getCsrfInput() }}
      <input type="hidden" name="action" value="contactForm/sendMessage">
      <input type="hidden" name="redirect" value="/careers/apply-now#form-thanks">

        Name
        <input id="fromName" type="text" name="message[fromName]" placeholder="Your Name" value="">
        {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

        Email
        <input id="fromEmail" type="text" name="fromEmail" placeholder="Your Email" value="">
        {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

        Phone
        <input id="phoneNumber" type="text" name="message[phoneNumber]" placeholder="Your Phone Number" value="">
        {{ message is defined and message ? errorList(message.getErrors('phoneNumber')) }}

      Position
      <input id="position" type="text" name="message[position]" placeholder="Position of Interest" value="" />

      Attach Resume
      <input type="file" id="attachment" name="attachment" />

    <input type="hidden" name="subject" value="Career Form Submission" />
    <input type="hidden" name="nothanks" id="nothanks" value="" />

        <input type="submit" value="Send">

  </form>


texts: Is it safe to make the 'app' folder writeable by the web server?

texts:
To allow one-click updates on my site, I need to make the Craft 'app' folder writeable by the web server.
Doesn't this present a security concern...to allow the actual php files of the application to be writeable by the web server?


texts: Multiple forms on same page.. Solspace Freeform

texts:
When there's two forms on a single page. (E.g Newsletter Sign up and Book a Tour) The submit button obviously validates both forms.

How can I differentiate between them both and make them independent?

{{ craft.freeform.form("newsletter", {
    id: "form-newsletter"
    }
}).render() }}

The other form is loaded into the page through a template via a custom field.


texts:
I have a model that contains a bunch of storage arrays where I collect results from various services I have written.

class Shipper_ResultsModel extends BaseModel
{

shipping categories for debugging

    protected function defineAttributes()
    {
        return array(
            'service'               => array('type'=>AttributeType::Enum, 'values'=>['post','courier','free','cantShip','needsQuote']),
            'options'               => array('type'=>AttributeType::Mixed,'default'=>[]),
            'boxes'                 => array('type'=>AttributeType::Mixed,'default'=>[]),
            'postShippingItems'     => array('type'=>AttributeType::Mixed,'default'=>[]),
            'courierShippingItems'  => array('type'=>AttributeType::Mixed,'default'=>[]),
            'freeShippingItems'     => array('type'=>AttributeType::Mixed,'default'=>[]),
            'cantShippingItems'     => array('type'=>AttributeType::Mixed,'default'=>[]),
            'quoteShippingItems'    => array('type'=>AttributeType::Mixed,'default'=>[]),
        );
    }

Each of this ShippingItems arrays is intended to hold an array of Shipper_ShippingItem models.

My issue is in building these arrays, I create new items and add them like this:

            $shippingItem = Shipper_ShippingItemModel::populateModel($data);

            //build our arrays of items
            if($shippingClass=="Courier Only"){
                $results->courierShippingItems[] = $shippingItem;
            }

But this results in the following error:

PHP Notice: Indirect modification of overloaded property Craft\Shipper_ResultsModel::$courierShippingItems has no effect

I think this is because I am not using array objects as such but I have to say I've  got a little confused here and various syntax experiments have resulted in ignoble failures.

Some guidance as to the right way would be much appreciated (and am I right in using AttributeType::Mixed for these?)

(This is all for a mega shipping calculator for Craft Commerce, should that matter)


texts: is it possible to edit an entry from the front-end when you're not logged in?

texts:
I'm working on a checkout process for a takeaway restaurant where anonymous visitors can place orders using guest entries.

In this stage the order is saved with a status of "unpaid". Once a visitor saves the order he's taken to a payment provider service where he pays for his order, once the order is payed the visitor is redirected to a page where the order status would be set to "paid" in a hidden form.

In order to accomplish this the aforementioned saved guest entry would have to be edited from the front-end. Is it possible to anonymously edit an entry?


texts: Locales and links not working as intended

texts:
I have taken over a project and Im having a small problem with locales.

It is running Craft 2.6.3016

A section has a locale “en” where the english URL format is “en/contact”, and the entry also have the slug “en/contact”…
So, I would expect this URL to be domain.com/en/contact/en/contact, no? But it is not!

When getting the URL with this code:

{{ craft.entries.section( 'contact' ).first().url }}

the url is “domain.com/en/en/contact”, this link does not work, but if I change it to “domain.com/en/contact” as I would expect it to be, it works!!

I have no idea what kind of dark magic that messes around with this, but maybe some of you got any ideas? Nothing seems to make any sense here.
Also note that the “en” folder in the public folder is called “en__” if I change this to “en” the locale stops working.

Any help appreciated!


texts:
I'm strangely having trouble with this simple Twig merge problem and can't find anything online. Simplified, let's say you had:

{% set users = [
    {name: 'Bill', age: 25},
    {name: 'Tim', age: 30},
    {name: 'John', age: 32}
] %}

How would you change, for example, Tim's age from 30 to 31?  I've tried:

{% set users = users[1]|merge({age: 31}) %}
{{ users[1].name }}: {{ users[1].age }}

But this doesn't work.


texts:
I'm trying to submit a form containing items from a users' cart, using A&M forms, but cannot seem to populate the table field with the items. I'm using the code below:

{% for item in cart.lineItems %}
    <input type="hidden" name="fields[selections][{{loop.index}}][col1]" value="{{item.qty}} x {{item.description}}">
{% endfor %}

For some reason, though, it's creating the rows in the table, but not actually populating it with any content. Any idea what to do to get it to work?

Thanks!


texts:
I am currently working with craft.

I want to create a filter with a dropdown list that will only display the images, that are related to the selected dropdown.

Is that even possible?

What I have:

    <select>
        {% for option in entry.selection.options %}
            <option>{{ option.value }}</option>
        {% endfor %}
    </select>
    {% for image in entry.bild %}

    {% endfor %}


texts: Set OrderBy on Grouped Query Involving Smart Map Field

texts:
I'm working with a Structure of resort locations. Each resort has a field address which is a Smart Map field. I'm trying to create an initial display page that groups the resorts based on their state (a Smart Map address part), but I would like to order the output first based on the state and then by resort title.
Something like.

Arkansas
Awesome Place
Best Place
Alabama
Alright Place
Better Place
Florida

I'm partially there using the following:
{% set resorts = craft.entries().section('resortsList').orderBy('title ASC').all() %}
{% set resortsByState = resorts|group('address.state') %}

And then outputting the list...
{% for state, resortsInState in resortsByState %}

{{ state }}

  {% for resort in resortsInState %}

{{ resort.link }} - {{ resort.address.state }}

  {% endfor %}
{% endfor %}

This gives me the list grouped by the state and ordered by the resort title which gets me partially there. I've tried adding address.state as part of the ordering declaration, but I'm only getting errors (Unknown column 'address.state' in 'order clause'). Is there a proper way I should be doing this?


texts: Getting Checkboxes to work on Frontend Forms

texts:
I have tried to follow the instructions listed here for checkboxes on frontend forms but have not been successful in implementation.

First, here is my code:

<form method="post" action="" accept-charset="UTF-8" enctype="multipart/form-data">

Push to GistServers for Gist {{ entry.id }}

<input type="hidden" name="action" value="gistClient/pushGistUnits">
<input type="hidden" name="entryId" value="{{ entry.id }}">

Select Gist Categories for Distribution.

{% if entry.gistCategories | length == 0 %}

        {% for option in entry.gistCategories.options %}
        <input type="checkbox" value="{{ option.value }}" name="fields[gistCategories][]"> {{ option.label }}

        {% endfor %}

{% else %}

    {% for checkboxOption in entry.gistCategories %}
        {% set checked = false %}

        {% if checkboxOption.selected %}
            {% set checked = true %}

        {% endif %}

        {% if not checked %}
            <input type="checkbox" value="{{ checkboxOption.value }}" name="fields[gistCategories][]" {% if checked %} checked="checked"{% endif %}>{{ checkboxOption.label }}

        {% endif %}

        <input type="checkbox" value="{{ checkboxOption.value }}" name="fields[gistCategories][]" {% if checked %} checked="checked"{% endif %}>{{ checkboxOption.label }}

    {% endfor %}

{%endif%}

{{ getCsrfInput() }}
{% if entry.socialPush == true %}
    {% set socialPush = "Push to GistServers"%}
    {% set socialPushBtn = "default"%}
{% else %}
    {% set socialPush = "Push to GistServers"%}
    {% set socialPushBtn = "success"%}
{% endif %}

<button class="btn btn-{{socialPushBtn}}  btn-sm btn " style="margin:10px 15px 0 0;" type="submit" name="fields[gistDraft]" value="0">{{ socialPush }}</button>

Now for screen caps showing behavior.

Before form submit

CP View after form submit

Frontend form after submit.

Ideally, After I submit the frontend form my users would be able to see all checkboxes again in case they need to change the selections. I am at a loss and would appreciate some rescue here.


texts: Trouble with merging Numbers in an Advanced Search

texts:
I have a search form where a user can enter width, height and depth and the search results will return any item that will "fit" into those dimensions. It works, but for some reason only if the depth is not set.

Form:

<input type="search" name="q" value="{{ craft.request.getParam('q') }}">
Width
  <input type="number" name="w" value="{{ searchWidth }}">
Height
  <input type="number" name="h" value="{{ searchHeight }}">
Depth
  <input type="number" name="d" value="{{ searchDepth }}">

The resulting query looks like this search3?q=&w=43&h=44&d=1000

For Results

{% set queryParams = {
  section: 'products',
  order: 'postDate desc',
  limit: 15
  } %}

{% set searchWidth = craft.request.getParam('w') %}
{% set searchHeight = craft.request.getParam('h') %}
{% set searchDepth = craft.request.getParam('d') %}

{% if searchWidth > 0 %}
  {% set finalWidth = searchWidth + 1 %}
  {% set queryParams = queryParams | merge({
    width: '<= ' ~ finalWidth
    }) %}
{% endif %}

{% if searchHeight > 0 %}
  {% set finalHeight = searchHeight + 1 %}
  {% set queryParams = queryParams | merge({
    height: '<= ' ~ finalHeight
    }) %}
{% endif %}

{% if searchDepth > 0 %}
  {% set finalDepth = searchDepth + 1 %}
  {% set queryParams = queryParams | merge({
    depth: '<= ' ~ finalDepth
    }) %}
{% endif %}

Which I merge with my original search:

{% set searchQ = craft.request.getParam('q') %}
{% if searchQ is not empty %}
{% set queryParams = queryParams | merge({
  search: {
  query: searchQ,
  subLeft: true,
  subRight: true
   }
 }) %}
{% endif %}

Everything works fine. If I enter 44 for h and 43 for w it does what it should, if finds all items smaller than the width and height. If I add something in the d, even 1,000 I get 0 results. If I output {{ finalDepth }} somewhere in the template it outputs without issue, but it finds 0 results when something is entered in the d search.

All three fields are number fields named width, height and depth. I have checked and rechecked and I am at a loss.


texts: Snipcart plugin don't recognize the webhook URL

texts: I've cloned the GitHub repository but the plugin won't recognize the webhook URL and the order is not placed.


texts:
I am actually doing on page SEO for a Craft site. I created 4 new pages. I have no idea how to publish them, put the links into a block on the home page, add an image to the content, and add to the menu via a dropdown. Is this all possible?

I am well versed in WP but not Craft.


texts:
Coming from the EE world, when I need a hierarchical site structure along with sections that have channel-type content, I use the Structure add-on for EE. Events, for example, go in a listing channel.

In Craft, while there is far more flexibility among the three section types: structure, channel, and single, there is no facility to create something akin to Structure for EE's listing channel.

Here's what I did instead. I created one master section of the structure type, and a whole bunch of different entry types.

Each landing page, for example, Staff, calls a template that aggregates content from a channel (which is distinct from the master section). This keeps content neatly segregated - I don't want items that are listings (news, events, staff, etc.) clogging up the master section - it would end up with hundreds of entries over time.

Here's the staff channel:

So the staff landing page, part of the master section just calls all the entries in the staff channel, and each entry links to a detail page.

{% for entry in craft.entries.section('staff') %}
  {{ entry.title }}
{% endfor %}

Overall, this method works very well. However, creating navigation is messy. Why? In order to load the staff detail page, I have to link to entries and their template which lie outside the master section, so I can't navigation or create breadcrumbs with Craft's {% nav %} tag or a for loop. Also, I have to hard code the full path to the staff detail template, which includes its parents.

My questions:

How are others solving this problem?
Is there a better way to make the staff detail entry url format more dynamic, in case the client decides to move the staff parent page elsewhere? Currently, if they move it out of about/staff, the staff detail urls are no longer correct.


texts: How to find entries that are not related?

texts:
Is there a simple way to find entries that do not have a relationship with another channel? I see similar questions here and here, but neither seem to work in this context (or I don't know how to adapt their answers).

I have 3 channels, 'accounts', 'clubs' and 'subscriptions'. Every 'subscription' has a required entries field (limit 1) for 'account' and 'club'. In this case, I'm trying to find 'accounts' that are not associated with a club (i.e. do not have a 'subscription'). Sounds like it should be easy, but not finding an answer.

Looking for something like {% set params = params | merge({ not relatedTo : subscriptions }) %}, which obviously doesn't work. I'm using merge because there may be other criteria as well (such as account status, etc).

Any ideas? Thanks.


texts:
I would like to set some variables for every entry within a section ('courses'), and then use those variables in loops that are filtering by entry types and categories.

Some simplified markup:

Required Courses

  {% for entry in craft.entries.section('courses').type('safsCourse') %}

{{ courseName }}

  {% endfor %}

Elective Courses

At least one agricultural science course

      {% for entry in craft.entries.relatedTo(65) %}

{{ courseName }}

      {% endfor %}

At least one social science course (3cr)

      {% for entry in craft.entries.relatedTo(66) %}

a href="{{ msuLink }}">{{ courseName }}

      {% endfor %}

As you can see, I'm using the variables msulink and courseName. The code works as intended if I include the following within each {% for entry... %} block:

{% set courseName = entry.deptCode ~ ' ' ~ entry.courseNumber ~ ': ' ~ entry.title %}
{% set msuLink = 'https://reg.msu.edu/Courses/Request.aspx?SubjectCode=' ~
    entry.deptCode ~ '&CourseNumber=' ~ entry.courseNumber ~ '#Results' %}

But I don't want to set those variables three identical times.

How can I set those variables once and use them when I'm pulling various subsets of my Course section entries?


texts: What is the table `templatecachequeries` for?

texts:
What is the content of templatecachequeries table for in Craft 3? Especially the column query?

And is it normal to have a lot of entries (+5000) even on a smaller medium sized page?

Or it is because of badly used {{% cache %}} tag? How does it relate?


texts:
In ExpressionEngine it was possible to have fields side by side.

So when creating a entry you had all options (for example for an image) in one row.

I can't figure out how to do that in Craft


texts:
I have a matrix table field that I want to render on a page. I've tried a few different things and nothing is working. I tried switch and elseif, but those weren't working. I'm no longer getting errors, but now - even though I have content in the fields - nothing shows up on the page.

It seems like it must be a templating error but I can't see what it could be. Any help would be greatly appreciated.

{% for block in entry.comparisonChart %}
{% if block.type == 'compareChartHeadingBlock' %}

{{ block.compareChartHeading }}

{% endif %}

{% if block.type == 'compareChartTwoBlock' %}
    {% for row in block.compareChartTwo %}

{{ row.chartTwoLeft }}

{{ row.chartTwoRight }}

     {% endfor %}
  {% endif %}

  {% if block.type == 'compareChartThreeBlock' %}
    {% for row in block.compareChartThree %}

{{ row.chart3Left }}

{{ row.chart3Center }}

{{ row.chart3Right }}l

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

Here is the matrix field:


texts:
Is there a way to specify in Craft 3 which hashing algorithm should passwords use?
I know craft 3 uses PHP's password_hash() function, my question is: is there a way of modifying the 2nd and 3rd parameter of that function via a craft config.

I'm trying to find a way of doing this without using a separate/custom column in the users table.

Thank you.


texts: Comparing 2 versions of an entry and highlighting the changes

texts:
I'm new to Craft and I'm wondering if Craft is able to display the differences within an entry in different versions.

Comparing 2 versions of the entry and highlighting the changes.

Something similar like most of the mergetools do.

I'm aware that the user can comment the last changes.


texts: "Your session has ended" modal popping up constantly

texts:
I know many other folks have posted this question over the years, but unfortunately none of the answers given so far are fixing this for me.

The problem: after logging-in on my staging server (this does not happen locally with MAMP), after a minute the "Your session has ended" modal comes up. Entering my password dismisses the modal for a second then it comes right back.

If I simply reload the page, I am still logged-in, but the modal will come back after another minute. Also, reloading causes my Craft identity cookie to keep its name but change its value.

If I look in /craft/storage/runtime/sessions, I can see that when the modal comes up, a new session file has been created, but is a 0 length file. All the session files have 600 permissions.

What I've tried/checked with no success:

session.auto_start = 0 is already set in the php.ini
session.save_path shows up correctly as
/home/<user>/craft/storage/runtime/sessions/
have tried both the overridePhpSessionLocation and requireUserAgentAndIpForSession config variables set to true and false
have deleted and recreated the sessions folder manually with 777 permissions
have deleted the sessions folder and let it be recreated by Craft (was created with 775 permissions)
I am not using any CDN/caching, or running this on Vagrant.

The server is running Apache/2.2.3 (Unix) and PHP 7.1.0.

Is there anything else I can try?


texts: Matrix Issues After Upgrading from 2.4 to 2.6

texts:
Running into some issues with matrix fields after upgrading from 2.4 to 2.6.

The matrix in the site includes a whole bunch of block types that are used to build row-based pages (e.g., Intro, Profile, News, Text, etc.).

When creating a new page everything works just fine at first. However, when you insert certain block types into the matrix, suddenly you can no longer reorder/collapse/add blocks in that matrix.

I notice that when it breaks, the following error pops up in the console:

Uncaught: TypeError: Cannot read property '0' of undefined - velocity.min.js

Anyone run into this or have ideas to what this might be? I can't seem to find a commonality between the blocks that cause the error and am not sure where to go with this.

Note: this particular matrix config has a ton of fields (we've had to extend the php memory limit etc. when saving changes to the config).

Tks in advance!


texts: How do I target the second item in an array with Twig?

texts:
I would like to select the second position in the array below. The problem is that this number is automatically changed. So I try to do this with .index function from Twig but I can not figure it out. Can someone help me?

array (
  7296680 =>
  array (
    ...
  ),
  7296635 =>
  array (
     ...
    'url' => 'vesten',
    'title' => 'Vesten',
  ),
)


texts: Do field values get serialized before validation?

texts:
I am learning to write my first plugin for Craft CMS 3.x

I have a field that gets displayed as a string, but is stored in the database as binary. When I validate it, I write:

public function getElementValidationRules(): array
{
    return [
        /* Other rules, */
        ['unique']
    ];
}

What I wonder is, will it get compared in its string form to the binary? Or will serializeValue() get called?


texts: How to filter entries by multiple checkbox field types

texts:
I've set up checkbox fields for photos in a photo gallery called "photoColor", "photoSubject", and "photoSize", all of which contain a bunch of options.
On the gallery page I have filters and I'm using Ajax to update the page when a checkbox is clicked.
<div id="filters">
 <input type="checkbox" name="colors[]" value="red" /> Red
 <input type="checkbox" name="colors[]" value="green" /> Green

 <input type="checkbox" name="subjects[]" value="human" /> Human
 <input type="checkbox" name="subjects[]" value="animal" /> Animal

 <input type="checkbox" name="sizes[]" value="small" /> Small
 <input type="checkbox" name="sizes[]" value="large" /> Large
</div>

I'm gathering the values of the checkboxes like this
  var colors = [], subjects = [], sizes = [];
  $('input[name="colors[]"]:checked').each(function() {
     colors.push($(this).val());
  });

  $('input[name="subjects[]"]:checked').each(function() {
     subjects.push($(this).val());
  });

  $('input[name="sizes[]"]:checked').each(function() {
     sizes.push($(this).val());
  });

Right now I can filter for one option of one field type, i.e. this works:
{%  set galleries = craft.entries.section("gallery").photoColor(value) %}

(where value = "red" for example)
But I'm struggling to figure out how to write the query to combine ALL 3 field types in an "or" query, i.e. the results only need to match one of those properties, not all of them.
In other words, if a user checks off red, green, animal, and small, it will show all the results matching either red, green, animal, OR small - not just red/green animals that are small.
In pseudo code, it would be something like:
{% set galleries = craft.entries.section("gallery")
  where .photoColor is red or green
   or .photoSubject is animal
   or .photoSize is small
%}

I've been searching StackExchange and trying things I saw in other answers for days, but none of the situations were quite like mine, so I haven't been able to get it to work. Can someone point me in the right direction? Any help is greatly appreciated.


texts: Feed Me Plugin: Can Match fields but feed not importing

texts:
I can detect and match up the fields from my json file but when doing the import I get the following error in the log:

No feed items to process.   3/28/2019 2:53 PM

error   Unable to reach data/case-studies.json. Message: File path cannot be found.

For some reason, it isn't picking up the file when doing an import. How do I resolve this?

I have validated the json file and it is correct so I'm stumped!


texts: Why am I getting "no sources available" when adding/editing a field of type Assets?

texts:
Anyone else suffering from this issue after doing an upgrade/update?

This may be in the category of bugs because it appeared to be working earlier today before upgrading Craft from the Free version to the Pro version I've been unable to save fields that are of type "Assets".

Current install is:
Craft Pro 2.1.2564 Released on 7/15/2014

The issue is pretty straight forward. Attempting to save or edit a field that is set to the type "assets" fails.

Additionally, the sources available for assets on the create new field page incorrectly indicate that no sources are available. Error reads "No sources exist yet."

I did a run down where I verified the directory paths were properly set, and the permissions for those directories were also properly set. Both checked out okay.

Additionally, uploads to all my defined sources work as expected. This issue seems to only impact fields.

Result of trying to save or edit a field produces an error that appears saying "save failed". No further warnings show up.

Here's a shot of the available sources defined on my install, these were defined after my upgrade if that makes a difference.


texts: I'm using amforms and would like to display all form errors at the top of my page, not just per field. I can't seem to find the answer in the docs. Is this option available?


texts: Is it possible to have entries only visible to logged-in users?

texts: I want to have a public and private (logged in users) section on the front-end. Is that possible on craft?


texts: Setting user password on creation / without full admin rights

texts:
I'm trying to set a password for a user account while logged in without Site Admin permissions (the user does however have 'Edit Users+Administrate users+Assign Groups and Permissions + Remove User permissions all enabled). - Despite this they still can't change a password for a current user or even create a new user with a set password that can login to the system.

This is partially problematic as 'Verify email address' is not something the company is interested in so I'm looking for a solution to create a user on the backend that can login once their account is created without verifying or really receiving any email and without having to give full administrative access to my client just to set passwords? Seems like something that should be achievable especially with the permission 'Administrate Users' enabled.

Cheers.


texts:
Is there a way to use a local url when my assets are stored in an S3 bucket?

I have a bucket I'm pointing to and in there I have a folder called backgroundImg with a background.png

I'm trying to access this from my CSS like

background-image: url('backgroundImg/background.png');

But it cannot find this url. It's building the url localhost/assets/backgroundImg/background.png

Is there any way to use the local path instead of an insanely long s3 url that is hardcoded?


texts: Is there an alternative to the Dukt Rest plugin for Craft 3?

texts:
I am using a combination of two Craft 2 plugins, Cookies and Rest to get the logged in status of a user. What is the recommended way of doing this in Craft 3?

{% set userReq =
  craft.rest.request
    .headers({
      Cookie: cookie
    })
    .url("https://api2.lumi.com/auth/current")
    .send()
%}


texts:
I am trying to create a new entry via a form post that will come from a third party, by doing this in my plugin's service class:

$entry = EntryModel::populateModel(array(
    'sectionId' => 1,
    'typeId' => 2
));

$entry->getContent()->setAttribute('reference', craft()->request->getPost('someReferenceField'));

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

The reference field is a custom FieldType (https://github.com/fuel-digital/Craft-Unique-Text-FieldType/blob/develop/uniquetextfield/fieldtypes/UniqueTextField_UniqueTextFieldType.php) where I am validating the submitted value is unique for this EntryType (in this case an Entry rather than a User/Asset/etc).

That FieldType works fine in the control panel but I'm getting an error when submitting via my plugin as $this->element is null within the FieldType's valueExists() method.

I can get around this by creating a new EntryModel like so:

/**
 * Checks if another entry exists with the given value
 *
 * @param  string $value The value to check
 * @return bool
 */
private function valueExists($value)
{
    if ( ! $this->element)
    {
        $this->element = new EntryModel();
    }

    $existing = craft()->elements->getCriteria($this->element->elementType)->first(array(
        $this->model->handle => $value
    ));

    return ($existing && $existing->id != $this->element->id);
}

But that means the FieldType will only work with Entry elements, and not Users, Assets etc.

As the plugin works fine in the control panel, I assume I'm missing something in my plugin service?