texts: How can I use the ElementAPI to get related entries based on two parameters?

texts:
I can successfully get entries related the "normal" way, but my list of possible results are getting quite large. Currently I am returning html mixed in with the data. It's obvious I need to get just the data and parse through it on the client side.

mytemplate.html

{% set paramOne = craft.request.getParam('paramOne') %}
{% set paramTwo = craft.request.getParam('paramTwo') %}

{% set relationParam = ['and'] %}

{% if paramOne %}
    {% set type = craft.categories.group('groupOne').slug(paramOne).first() %}
    {% set relationParam = relationParam|merge([{ targetElement: type }]) %}
{% endif %}

{% if paramTwo %}
    {% set type = craft.categories.group('groupTwo').slug(paramTwo).first() %}
    {% set relationParam = relationParam|merge([{ targetElement: type }]) %}
{% endif %}

{% set entries = craft.entries.relatedTo(relationParam) %}

I'm not quite sure how to translate that into elementapi code (for lack of better words).

elementapi.php

return [
    'endpoints' => [
        'myfile.json' => function (??) {
            $paramOne = craft()->request->getPost('paramOne');
            $paramTwo = craft()->request->getPost('paramTwo');

            return [
                'elementType' => 'Entry',
                'criteria' => [
                    'section' => 'mysection',
                    'relatedTo' => [
                        'and' // and needs to go somewhere...
                        'targetElement' => ??, // This is the entry
                        'field' => ?? // This is the category?
                    ],
                ],
                'transformer' => function (EntryModel $entry) {
                    return [
                        'title' => $entry->title
                    ];
                },
            ]
        }
    ]
];


texts: Can Feed Me create an example feed file from local fields?

texts: While trying to configure a feed and looking for documentation, I wished Feed Me could just tell me what syntax it was expecting. Is there a way to take the fields you've got and generate a file to feed them?


texts: Is any way to add translations for Braintree Gateway dropin interface?

texts:
The correct way to add translation to an instance of braintree.dropin is to add options.translations array when calling the braintree.dropin.create method, for example:

if ($dropinUi.data('locale') == 'el') {
          options.translations = {
            payingWith: "Πληρωμή με {{paymentSource}}",
.... and then ....
braintree.dropin.create(options, function(err, dropinInstance) {
....

work fine, but I can do it only directly in DropnUi.js file from /vendor/_path_to_braintree-gateway and this is wrong way.

What is right way to extend gateway and add translation fields? Via custom module with event or something else?

Thank you.


texts: How can I access the file extension of an asset?

texts:
Migrated from a Slack #help channel question

Jason Mayo [09:53 16/6/15]

Is there anyway to output what file type an assets file is? E.g. if its a Jpeg, SVG or Gif etc.


texts: Custom URI to exclude entries in structure

texts:
I have a structure where the Entry URI Format is {parent.uri}/{slug} - what I'm looking to do is conditionally not include entry slugs within the uri based on a show/hide setting in the entry.

For example, I might have structure where an entry, sub-page2 has a uri like so page/sub-page/sub-page2 but if there is a setting on sub-page to exclude it, it's uri should be page/sub-page2

This would mean that the conditional to show it should only be considered if it's being called as a parent. sub-page should still be accessible from page/sub-page - trying to find a way to achieve this?


texts:
I am currently using Craft to manage only certain pages on a site. The static pages all end in .html but Craft's pages don't. Is there a way to rewrite them via Craft to add .html or do I have to do some .htaccess wizardry? I only want to rewrite the pages and not the categories (for example, /news/).

If I can achieve this, should I? Are there enough SEO benefits to a consistent URL format? I've also read using .htaccess in this way may affect SEO negatively, which is why I'm wondering if there's a way of doing it with Craft.


texts: Caching and Memory problems. What is best caching method

texts:
I'm working on a website for a music / artist agency.
On the homepage we need al the artist entries. More than 200.

Each artist profile has an image, an image color extruder picker, some tags, relation, etc etc.

Without caching I have a lot of queries. But the page can render.
If I enable cache, the server runs out of memory sometimes. And when I enable an entry, or edit an entry, the whole cache with the artist loop gets cleared.

This is my code.

{% block content %}
    {% cache for 1 week %}
        {% set cases = craft.entries({
            section: 'artist',
            order: 'title',
            limit: null
        }) %}

                {% for entry in cases %}

                        {% set tags = entry.genre %}
                        {% set agent = entry.agent %}
                        {% set image = entry.introFoto.first() %}

                        ...
                        ...
                        etc etc

                {% endfor %}
    {% endcache %}
{% endblock %}

So can I cache individual entries? Like so? When someone edits an entry, only that entry cache get cleared?

{% block content %}

        {% set cases = craft.entries({
            section: 'artist',
            order: 'title',
            limit: null
        }) %}

            {% for entry in cases %}
                {% cache for 1 week %}

                        {% set tags = entry.genre %}
                        {% set agent = entry.agent %}
                        {% set image = entry.introFoto.first() %}

                        ...
                        ...
                        etc etc

                {% endcache %}
            {% endfor %}

{% endblock %}


texts:
I've got my news entries paginated and I have a featured entry on the first page so I'm wondering what the best approach would be to filter by category. Here is what my template looks like:

{% extends "_layout" %}
{% set title = "News" %}

{% paginate craft.entries.section('news').featured('not 1').limit(6) as pageInfo, pageEntries %}
{% set segment = craft.request.segment(2) %}
{% set pageCats = craft.categories('newsCategories').slug('segment') %}
 {% block content %}

Company News

    {% if pageInfo.currentPage == 1 %}
    {% for featuredEntry in craft.entries.section('news').featured('1') %}

                {% for image in featuredEntry.featuredImage %}

                {% endfor %}

{{ featuredEntry.title }}

                {{ featuredEntry.body.getPage(1) }}
                Continue reading

    {% endfor %}
    {% endif %}
    {% for regularEntry in pageEntries %}

{{ regularEntry.title }}

                {{ regularEntry.body|hacksaw(words='25', allow='
', append='...') }}
                Continue reading

    {% endfor %}

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

{% endblock %}

{% nav category in craft.categories.group('news') %}

{{ category.title }}

{% endnav %}


texts:
I'm using locales to drive several sites/domains from one build.
I have set up a bunch of 301 redirects in the .htaccess to capture and redirect previous URLs. I've used RewriteCond to target the rules for the individual sites but these aren't working as I'd expect.

RewriteCond %{HTTP_HOST} ^site1\.com [NC]
RewriteRule ^news.asp /news/news-listings? [R=301,L]

RewriteCond %{HTTP_HOST} ^site2\.com [NC]
RewriteRule ^news.asp /news-galleries/news-listings? [R=301,L]

If I enter site2.com/news.asp I am redirected to the Rule stated for site1 so the user is redirected to site2.com/news/news-listings which (obviously) returns a 404 error message. Any thoughts on how should be doing the above properly?


texts: Order entries by "recently modified" date time in control panel

texts:
Ok somebody ought to start asking the Totally Green questions, it may as well be me.  How do I show the date and time an entry was last manipulated in the control panel?

I produce video more than websites, though that is rapidly changing, and will so even more as the canvas becomes the new After Effects, so I am giving up and in and I'm going to ask all the questions total neophytes would, if it's okay with you people.  Eventually I'm gonna announce my first plug-in, pat myself on the back, and drink a shot.


texts: How can I return specific matrix rows based on criteria?

texts:
So let's say I have the following code. I have the data to retrieve the entry I want, But I only want to return some of the matrix rows based on some criteria.

Example Code:

{% set entryId = 1 %}
{% set entry = craft.entries({ section: "mySection", id: entryId }).first() %}

{% set myMatrixOutput = entry.myMatrixField.find({ someFieldInTheMatix: 2 }) %}

{% for row in myMatrixOutput %}
    {{ row.someFieldInTheMatrix }}
{% endfor %}

I can't get that to work it simply return me everything. I know that I could adjust my loop to be

{% for row in myMatrixOutput if row.someFieldInTheMatix == 2 %}

But say I have a large number of rows in the matrix field it would seem a waste to do all that looping if it could just bring back the correct results?


texts: We'd like to keep the revisions feature active on our site, but a few of our content sections are synced with a third-party API and we don't need to keep a revision at all. Is there a way to set maxRevisions to 0 for specific sections?


texts:
I have a landing page on my site where I want to list a group of sections that have entries. I also need to access the section handle of that same group of sections.

I am having problems getting the section handle for the sections.

Currently I get an error back that says impossible to access attribute ("handle") on a string variable.

        {% set specialEntries = craft.entries.section(['sec1','sec2','sec3']) %}

        {% set grouped = specialEntries|group('section') %}
        {% for section, specialEntries in grouped %}
            <h1>{{ section }} - {{ section.handle }}</h1>
        {% endfor %}


texts:
I wanted to build a commerce website using Craft 3. And I wanted to create parent registration form so each parent will have an account to use on the site. Then after they sign in I want them to be able to add their children.

Is this possible to do using Craft 3. The only thing I found is user registration form on the documentation.

If there is a blog or documentation that shows how to integrate this feature using Craft 3 or is there anything I missed so far.


texts: Redactor adding extra paragraph and br tag when entering and exiting HTML source mode

texts:
I'm currently on the latest version of Craft (2.6.2785). When I edit Redactor content I have no issues, but if I enter HTML mode and exit it I end up with

 prepended to the content.

Here's a GIF of this issue.

I updated from version 2.5.2767 and that version does not have this bug.

In case it helps, here's the JSON config for the Redactor field I'm referring to:

{
  "buttons": ["html", "formatting", "bold", "italic", "unorderedlist", "orderedlist", "link", "file", "image", "video"],
  "plugins": ["fullscreen", "video", "table"],
  "toolbarFixed": true
}


texts: Hundreds or thousands of posts in a structured channel?

texts:
I'm looking to create a very simple website where a user can add items to their own personal feed over time. So by default it's date ordered, but you maintain the ability to sort the order a little bit if you want. So one day I might add a photo, the next day I add a video, the next day I add some text. All these items build up over time and it just gets bigger and bigger. Over the years you might end up with hundreds or thousands of items that you've added.

Matrix seems perfectly suited to something like this – where each item is a new block. Except for the fact that all of the items would need to live in a single entry. And I just can't see scaling that very big if everything is in one entry.

So the alternative would be to have each item live as a new post in a channel. This seems like it would make more sense, especially as you get into the hundreds or thousands of items. But then how would I maintain the ability to sort the entries? If I made the channel structured, would that be adequate? And would there not be any issues with having it scale to hundred or thousands of posts in a structured channel?

Basically I'm just trying to lay a firm foundation where I could theoretically have hundreds/thousands of users each with hundreds/thousands of posts.

Also, this is basically a vision for a web app that would have a front end interface on it. Is something like this pushing Craft past it's abilities for what it was designed for?


texts: Ordering events using Solspace Calendar (Craft CMS)

texts:
I'm trying to retrieve a list of events that are ordered by calendar and also event title.

I can't get any of the ordering values to have any effect.

set events = craft.calendar.events({
    dateRangeStart: '2017-08-27',
    dateRangeEnd: '2017-08-27',
    order: 'calendarId ASC'
})

All I ever get is the results by element.id.

The documentation says 'use any of the keys above' and then uses a key that's not listed above. It suggests 'startDate' which is an event property, so I'm assuming that I'd be allowed to use event 'title'...?

I could just get all the events for the day and then group and sort in Twig but that's a terrible spot for grouping and sorting, and the docs suggest that the ordering of results works.

Does anyone know what I'm getting wrong?


texts:
I'm trying to register a user from the front-end and assign them to a specific group. I know that via control panel I can set a default user group, but there is a registration instance where I need the registrant to be assigned to a different group.

I tried this to no avail...

<input type="hidden" name="groups" value="4">


texts:
I am trying to filter entries based on multiple field value ranges.
For example: All entries where my customField (type: number) is between 0 and 10 OR 20 and 25.

It's straightforward to filter by one range:

{% set results = craft.entries({
  customField: ['and', '>= 0', '< 10']
}) %}

How would I add multiple ranges for the same field to the above query?


texts:
We're adding advertising to our Craft site. The ads come from our business members and are displayed randomly with article pages, based on tags and categories. All that is working fine.

The question comes up, how to report impression counts of the ads back to the advertisers? I'm newish to Craft; I don't know if it is possible to write back to a field of an asset (displayCount = displayCount + 1 kind of thing).

Any ideas or suggestions would be appreciated.


texts:
I would like to let my static assets (JS, CSS and images file) close to my templates files.

public/
templates/
    css/
    images/
    scripts/
    template.html

Until now, I didn't find a clean way to access these files.
{% includeCssFile %} and {% includeJsFile %} works, but I get strange "compiling" issues with my javascript "templates" saying unclosed comment.

Anyway, does a clean solution, other than copying these files to public, exists ? A variable like siteUrl pointing to the right folder ?


texts:
I've got a plugin where I've written a simple recursive array search to find an array within a nested/multidimensional array which contains a certain value.

private function arraySearch($haystack,$needle,$depth = 1)
{
    foreach($haystack AS $key => $value) {
        if (is_array($value) && array_key_exists('title',$value) && strtolower($value['title']) == strtolower($needle)) {
            return $value;
        } elseif(is_array($value)) {
            $depth++;
            $this->arraySearch($value,$needle,$depth);
        }
    }
}

With some logging within this function I can see that it works and returns at the correct time but when I call it in my plugin methods the response is empty.

For example, if I wanted to get an array which contains a title key and the value for this is venue, I'd type:

$result = $this->arraySearch($array,'Venue');

Applied to the following array:

Array
(
    [pages] => Array
        (
            [0] => Array
                (
                    [elements] => Array
                        (
                            [0] => Array
                                (
                                    [type] => text
                                    [isRequired] => 1
                                    [name] => question1
                                    [title] => Venue
                                )

                            [1] => Array

So this should return the array $array['pages'][0]['elements][0] but $result` seems to be empty.

Any suggestions?

Cole


texts: Set conditional parameter to not output "dateUpdated" field, when entry is first time created

texts:
I was going through my code for testing purposes and found out, that When entry's first time created, it also outputs data from the field "dateUpdated".
I'm assuming, when an entry is first time created it is also first time updated.

So I'm trying to write a conditional statement to not output "dateUpdated" for entries, that were first time created.

So far I didn't come up with anything, because I'm not sure If what I'm assuming is true.

For the start.

{# Date #}

     {{ "published"|t|ucwords }}: {{ entry.dateCreated is empty ? "" : entry.dateCreated|date("d.m.Y") }},

{% if entry.dateUpdated %}

            {{ "updated"|t|ucwords }}: {{ entry.dateUpdated is empty ? "" : entry.dateUpdated|date("d.m.Y") }},

{% endif %}
{% if entry.expiryDate %}

            {{ "expire"|t|ucwords }}: {{ entry.expiryDate is empty ? "" : entry.expiryDate|date("d.m.Y") }},

{% endif %}


texts: Table attributes not customisable for nested entry sources

texts:
Using a plugin, I have added some nested entry sources to some of the default section entry sources in my site.

For example:

'section:6' => [
    'label' => 'News',
    ...
    'nested' => [
        'foo' => [
            'label' => 'Foo',
            ...
        ],
        'bar' => [
            'label' => 'Bar',
            ...
        ]
    ]
];

Now, for the main entry source (section:6), I am able to select the visible columns (table attributes) that appear in the element index listing. However, that selection of table attributes does not filter down to the nested entry sources. When I click on a nested entry source, the default table attributes are utilised rather than the attributes that were selected for the parent source. I want my nested entry sources to utilise the same table attributes as the parent entry source.

I did some digging around in the Craft CMS code and database, and it appears as though the craft_elementindexsettings table only saves the table attributes selected for top level entry sources and not nested ones. So when the ElementIndexesService is called upon to getTableAttributes for the nested source key, it is returning the default attributes (as evident below).

public function getTableAttributes($elementTypeClass, $sourceKey)
{
    ...

    // Is there a custom attributes list?
    if (isset($settings['sources'][$sourceKey]['tableAttributes']))
    {
        $attributeKeys = $settings['sources'][$sourceKey]['tableAttributes'];
    }
    else
    {
        $elementType = craft()->elements->getElementType($elementTypeClass);
        $attributeKeys = $elementType->getDefaultTableAttributes($sourceKey);
    }

    ...

    return $attributes;
}

Hopefully someone can shed some light on why I cannot customise the table attributes of the nested entry source.

Here is a real life demonstration of the issue using Pixel and Tonic's Happy Lager demo site and Category sources plugin.

As you can see above, in my 'Alcoholic' top-level entry source, I've specified custom columns/attributes so that the 'Heading', 'Section' and 'Entry Type' are also included in the element index listing for the entry source.

However, if I then click one of the nested entry sources, 'Beer' for instance, those 3 custom columns/attributes are no longer present as is evident below.

In my opinion, the expected behaviour would be that the nested entry sources would utilise the custom columns/attributes defined for the top level entry source. So  'Heading', 'Section' and 'Entry Type' should have been visible when clicking on 'Beer'.

I expect it's more work technically, but it might also be useful if it were possible to independently configure the columns/attributes of the nested entry sources too.


texts: Getting Invalid Type Error with no Key Path Value

texts:
I am trying to specify a section to publish an article to and am using the addMetaData method in Article.php which my article class is extending.

The method in the base class allows for nested array properties by using a dot delimeter syntax so I have this right now in the init method of my article class

$this->addMetadata("links.sections", "https://news-api.apple.com/sections/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");

Here is the doc from apple news https://developer.apple.com/documentation/apple_news/code

[code] => 400
[message] => HTTP/1.1 400 Bad Request
[response] => stdClass Object
    (
        [errors] => Array
            (
                [0] => stdClass Object
                    (
                        [code] => INVALID_TYPE
                    )

            )

    )

)
 in /app/vendor/chapter-three/apple-news-api/src/PublisherAPI/Base.php on line 197

The error message isn't providing a key path with a field name so I'm a little lost as to debuggin the error.

If anyone has experience with the plugin and can point me in the right direction that would be great!


texts:
I'm creating a multilingual site and I'm looking to pass some additional configuration data to Twig so I can use it in my template. For example, suppose I have a configuration like this:

{
  "serviceName":        "arabic",
  "language":           "ar",
  "textDirection":      "rtl",
  "socialMediaButtons": ["twitter", "facebook"],
  ...
}

I'd like to use this data to set the dir attribute in my template:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="{{ craft.locale }}" dir="{{ config.textDirection }}">
<head>
  ...
</head>

Is there an easy way to do this?

My project structure looks like this:

Where each locale directory has a config file.

Thanks!


texts:
I have an existing ExpressionEngine site which I'm looking at moving to using Craft instead.

Only really had a quick cursory glance at the system so far but a little confused on a few things.

Say I have top level menu with items such as

Home
Services
Company

For instance let's say in the services menu there are some subpages such as :

Service 1
Service 2

and so on and so forth. On the existing site we are using the Structure module which allowed each of those services to have a url such as :

http://www.mysite.com/services/service_1

and so on. That's all fine so far as long as each item in that menu is a service. Now let's say for arguments sake that we want a standard informational page thrown into that menu. From what I see so far with Craft (really hoping I'm wrong on this though) if I create say an information section and then link to that in my navigation then I'm going to end up with something like:

http://www.mysite.com/information/my_information_page

What I'd like to end up with however would be :

http://www.mysite.com/services/my_information_page

This makes more sense to me with the menus and URLs for people to remember.

I know I must be missing something obvious here but just not quite seeing what yet?

The above is just a very literal example but the whole site is like this in that the subsections can contain any kind of content but they still follow a good URL scheme.

Thanks in advance for any help with this.

Best wishes,

Mark


texts:
I have multiple feeds being run via cronjobs, and would like to display front end "Last updated: 15:38 18. June"

Does anyone know if its possible to get the timestamp of the last import from a specific Feed Me feed?

I've found the following from the docs, but it seems to be pointed towards running a feed. I just want to get data out of the log from a feed.

{% set params = {
    url: 'http://path.to/feed/',
    type: 'xml',
    element: 'entry',
    cache: 60,
} %}

{% set feed = craft.feedme.feed(params) %}


texts: 403 Error on homepage of second language

texts:
We are trying to setup a second language. We've gone through the steps and created a second website, we defined the base URL as @web/de for the second language (German).

The deeper sections are working fine (e.g. www.url.com/de/kontakt). However we can't get the second homepage to work on the URL www.url.com/de. We get a 403 access denied from nginx. We followed all the steps in the documentation (https://docs.craftcms.com/v3/localization.html), but can't get it to work. I assume we are missing something or forgot to do something.

The homepage is a single. In sections, we have left the URI blank for both, the default english site as well as the german site. The template is the same for both.

As a dev environment, we are using Local by Flywheel on a local workstation.

Here are some screenshots of our configuration:

Site overview:


texts: As I put the CSS files on the public root folder of the live site, the CSS doesn't load on the live site.


texts: How to protect elements that are being edited during project-config/sync?

texts:
Some situations:

An editor is editing an entry in the CP while an admin runs project-config/sync.
A user starts a front end form to create a new entry before project-config/sync is run, but submits it after.

What happens to the entry being edited in these situations? Especially if the entry structure gets changed during the sync? I'm afraid of pushing changes that might break the form submission.

If the sync will cause a submission error, what are some ways to work around that? Can I do something like API versioning so the previous structure can be used to submit the edits?


texts: How to persist locale in site navigation?

texts:
I've got a bi-lingual site running nicely, /en/news/news-item displays the English version and /cy/news/news-item displays the Welsh version. Great!

I can't figure out how to get the URLs for the main site navigation to respect the currently used locale though. For example;

If I'm on the page: http://craft.dev/cy/news/news-title the main site navigation should list 'news' and 'artist' with a /cy preceding the URL (/cy/news and /cy/artists). Instead it's spitting out /en/news and /en/artists.

The code I'm using to get the URLs for the navigation is:

News

Artists

What am I doing wrong?


texts: Elements API - How to order / limit the output with an asset field of an entry

texts:
I recently started using the Elements API and I made up a recipe site as an example project. It's pretty easy to output the recipes as json data.

But I now want some more control about the output of the data and only query a specific subset of the recipes. As long as I have the data needed for the selection directly in the recipes entries it's easy to filter or sort them accordingly. However sometimes I might want to manually pick and order entries. One solution would be to create extra attributes in the recipe entries, but this seems messy.

I would like to do that with an entry selection field since this seems to be the most intuitive option for content authors. My question is how can I use the data of an entry field to limit the output? My current solutions seem really bad:

I simply query each entry separately by id, but this seems like a terrible idea in particular for a larger selection.
I load all data and do the cleanup in Javascript. Even though the images at least wouldn't get loaded this way it seems like an increasingly bad idea with an increasing number of total entries.
The best solution for now seems to create an endpoint for the entry that contains the entry selection field and use the transformer to output the all the needed data - I miss the nice pagination / meta data that way however.

'transformer' => function(Entry $entry) {
     $selection =  [];
     foreach ($entry->selectedRecipes as $block) {
          $selection[] = [ array(
                          'title' => $block->title,
                          'id' => $block->id,
                          ...
                           )
                         ];
             }
     return [ 'recipes' => $selection,

This seems like a really basic problem and any hints on how to solve this problem are greatly appreciated.

Thank you


texts: What causes an entry's field to be marked as "modified" when the entry is saved?

texts:
When an entry is saved, what causes the entry's individual fields to be marked as "modified" in the POST request?

I'm trying to troubleshoot an issue where a modified Redactor field that is a child of a Neo field is not being saved. When I examine the POST data in the debug bar, I see that the field's updated content was posted, but the 'modified' key in the array is still set to '0'.

What's interesting is that if I modify the Redactor field by typing words in it, the field's 'modified' key is set to '1' in the POST data, as expected. However, if I try to just add a single period; highlight text and press delete; or try to copy and paste text into the Redactor field, the 'modified' key is not set to '1' when I save.

So it appears that, in order for the Redactor field to be marked as "modified", I have to type a certain amount of text into the field.

Edit: After more testing, it appears that adding or deleting a single character is not enough for the field to be marked as 'modified'. However, if you add at least two characters, with a pause between each character, the field will correctly be marked as modified. If you type a word quickly, and then save, the field is not marked as modified. If you type a word and be sure to leave at least a second's pause between typing two of the characters, the field is marked as modified.

I'm trying to troubleshoot this issue and identify the root of the problem; is this an issue with the Redactor plugin not reporting that its field has been changed? Is it an issue of the Neo plugin getting in the way of its child field's Redactor field reporting the change, or is an issue with Craft, itself, not picking up on the field being modified?

Since the issue is in the request's POST data, it appears that this is a JavaScript issue, and not a server-side one (though I could be wrong, because I don't know all the ins and outs of how Craft saves entries).

If anybody has any suggestions of where the problem might lie, I'd be very grateful!

The versions involved are:

CraftCMS: 3.4.10.1
Redactor: 2.6.1
Neo: 2.6.5.1


texts:
I think I might be missing something here but it seems twig tags aren't parsed within  tags? Is there any way they can be, e.g.:

<script>
var homepageStandfirstAnchors = [<% for anchor in homepage.homepageStandfirstAnchors %>[{{ anchor.text }},{{ anchor.section.handle }},{{ anchor.anchorLink }}],<% endfor %>];
</script>

doesn't work as expected.


texts:
For some reason there is not really a clear mention on the Craft documentation about this. And I couldn't really find anything in here that explains it either. I know this is kind of basic knowledge for Craft, so here goes:

I made a single section called 'work' and a folder of the same name in my templates folder (with an index.html inside). I try to link to it with http://www.mydomain.com/work/ but it doesn't work! It gives a 404 error. I don't understand why it doesn't work. I don't remember having trouble with this before.

What can possibly go wrong?

How do I create simple links like this to other singles?


texts:
As some of you may have seen I've been asking on here and on Slack regarding the best way to go about creating a navigation on a site.

As yet, nothing I have tried is working and any code that I've been given to try also hasn't worked. (Thanks to everyone who has given code so far though).

Therefore I have literally stripped down everything in the hope that someone might be able to tell me where I'm going wrong as I'm sure that something as simple as this shouldn't be as difficult.

I have a completely fresh install of Craft 2 with the standard templates that come with Craft and I have then created a Structure called (creatively enough) Navigation of which the hierarchy can be seen below.

Home
Services
---- Service 1
---- Service 2
--------- Sub Service 1
---- Service 3
Galleries
---- Gallery 1
---- Gallery 2
............

The above is actually just an example but reflects the sort of items that could go into the site.

Any of the items above could also be either an entry, a single or a template that has a channel on it and so on and so forth.

First up I'm not sure if I actually need to place any information into the Entry URL Format and Entry Template settings for the section as I'm guessing these aren't maybe all that important as the section is literally just being used for creating navigation on the site. That said I did fill them out with standard information just in case.

Next on the standard news/_entry.html template I placed this code :

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

        {% nav page in pages %}

                {{ page.getLink() }}
                {% ifchildren %}

                        {% children %}

                {% endifchildren %}

        {% endnav %}

This allows me to spit out the entire navigation which is good so far but in my Structure section I have an Entries field which allows me to choose an entry. I first of all have no idea of how to spit out this as the link instead of the {{ page.getLink() }} code above.

My Entries field is called singleEntrySelector and I tried {{ page.singleEntrySelector }} to see if it would spit anything out but that didn't work and I got an error on the page.

So I'm wondering how do I go about spitting out the content of the singleEntrySelector field so that my navigation items can point to the correct URL?

Once that is working I'd like to have it so that when I'm on say Sub Service 1 that I can create a secondary navigation on the page which will show me everything from Services down to (in this example) Service 3 so pretty much a very standard secondary navigation output.

That should (I'm hoping) allow me to do what I need here although I am definitely open to other ways of approaching this if I'm completely seeing things wrong here?

Many thanks,

Mark

P.S. I'd also like to be able to in the end spit out the navigation using whatever HTML code I need to as I will be utilising this on a responsive site and so have no idea yet as to what code I will need to encapsulate it all in. Therefore if the {% nav %} tag isn't the right fit here in that it won't allow me to do that then I'd really appreciate being shown how to spit it out in some other way that will allow me to do just that.


texts: activateAccountSuccessPath doesn't work as expected

texts:
I have a bi-lingual site with public registration, the site has a front-end registration form which when completed sends the user to an 'activation pending' page correctly, then sends an email off that the user must click to activate the account.

Clicking that link takes the user to the normal Craft login page, and I am expecting it to instead take the user to the page I've got set up as a welcome message and FAQ.

My code is:

return array(
'*' => array(
    'omitScriptNameInUrls'       => true,          // Whether Craft should omit the script filename currently being used to access Craft (e.g. index.php) when generating URLs
    'cpTrigger'                  => 'secretadmin', // The URI segment Craft should look for when determining if the current request should route to the CP rather than the front-end website
    'maxUploadFileSize'          => '16777216',    // 16Mb
    'phpMaxMemoryLimit'          => '128M',        // The maximum amount of memory Craft will try to reserve during memory intensive operations such as zipping, unzipping and updating
    'enableCsrfProtection'       => true,          // Protect against Cross Site Request Forgery; http://buildwithcraft.com/help/csrf-protection
    'searchIgnoreWords'          => array('a',
                                          'the',
                                          'and',
                                          'as',
                                          'if'),   // Words that should be ignored when indexing search keywords and preparing search terms to be matched against the keyword index
    'purgePendingUsersDuration'  => 'P1W',         // If a user hasn't confirmed their registration in under a week, delete it.
    'activateAccountFailurePath' => array('en_gb' => '/accounts/activation-failed',
                                          'cy_gb' => '/accounts/activation-failed'),   // Where to send failed account activations (only from front-end registration forms)
    'activateAccountSuccessPath' => array('en_gb' => '/accounts/activation-succeeded',
                                          'cy_gb' => '/accounts/activation-succeeded'), // Where to send successful account activations (only from front-end registration forms)
),
...
);

The docs do say the activateAccountSuccessPath only applies to front-end registration, but that's what I'm doing?

What have I misunderstood or didn't set correctly?


texts: Where can I edit the "Service Unavailable" page/template?

texts:
Sorry if this is an obvious thing - can't seem to find an answer in the docs.
Where can I edit the system offline message? "service unavailable"


texts:
I am looking for a plug-in that would allow me to add a site wide announcement banner to the top of a page. Much like the one in the image below:

I'm new to Craft and have gotten my site up and running but can't seem to figure out a simple way to do this.


texts: Verbb Feed Me for Craft 3 - Possible to read assets from local disk?

texts:
In https://verbb.io/craft-plugins/feed-me/docs/content-mapping/field-types#assets the documentation says yes, but I cannot get it to work.

I also find the documentation confusing: "You should supply the filename only, excluding the full path to the asset". How can it even know where to get the file then?


texts: Lightspeed retail POS integration with Craft Commerce

texts: Does anyone know of a plugin to integrate Lightspeed retail and Craft Commerce?


texts: How do I loop through two sections as one set

texts:
I'm trying to loop through two separate channels, but combined together. And then just check which channel the entry belongs to in the loop to display it correctly. This is how I had it done in EE, but I can't seem to find a way with Craft.

{exp:channel:entries channel="press|in-the-press" orderby="date" dynamic="no" limit="10"}


texts: Get related entry data within a plugin (ElementCriteriaModel) without extra queries

texts:
I have the following code:

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

// Loop
foreach ($criteria as $entry)
{
    echo $entry->id.'
';
    echo $entry->title.'
';
    echo $entry->sport.'
';
}

The sport field is an Entry field, pointing to an entry in a different channel. My question is, how can I get the data from the related entry (i.e. the title) without an extra query per row? Can I eager load it? Or get the sport entries in a separate query and then combine the data?

I need to get the title of the related sport entry. The following works but gives an extra query for every row:

$entry->sport->first()['title'];

Anyone? Thanks in advance


texts: Adding custom actions to Craft Commerce orders page

texts:
I'm trying to add custom actions to the order page. Following the documentation on hooks and Element Actions, I did this

In my main plugin file (OrderExporterPlugin.php)

public function commerce_addOrderActions($source)
{
    return array(
        new OrderExporter_ExportElementAction()
    );
}

In the folder elementactions (OrderExporter_ExportElementAction.php)

class OrderExporter_ExportElementAction extends BaseElementAction {

   public function getName()
   {
    return Craft::t('Export file');
   }

}

The hook is active, but sends an error with the message "Class 'Craft\OrderExporter_ExportElementAction' not found" when trying to access that class

My IDE recognizes the class, so I think the namespaces are fine


texts: craft cms how to modify redactor image upload path

texts:
So for my assets field types, I have the Asset Location (Where selected assets should be stored.) set to:
{owner.type.name}/{owner.slug}

this neatly puts all the files I upload via the asset field into subfolders for me (sorted by entry type and entry slug). However, when I upload images via the Redactor field, I can't seem to find a way to modify Redactor's image upload path to be similar to the ones I have for my assets field. Hence I am wondering whether this could be done (to modify the image upload path for redactor)?


texts: How do I include record relationships in validation?

texts:
Say I have a record defining a foreign key relationship which is set to required, such as:

public function defineRelations()
{
    return [
        'type' => [
            static::BELONGS_TO,
            'Events_EventTypeRecord',
            'required' => true,
            'onDelete' => static::CASCADE
        ]
    ];
}

If I try to save the record with typeId not set I'll eventually get a database exception but the error won't show up if I call $record->validate().

How do I make a relationship fail validation?


texts: Multiple Photos/Assets in one upload entry

texts:
I'm having a bit of a problem with using craft currently. My site has a gallery section where I would like to mass-upload image files to an entry which is in the area:

admin/entries/photos

However, when I upload the files in the following fashion, by selecting all of the images, uploading them and then inserting them into the photo entry, the desired effect is not found.

I upload all of the images and select them in the interface
I then am met with this screen, with all of the images I selected in one section.
However, only the first image from the upload stack is shown on the live page. (The last screenshot is confusing, I have uploaded those photos one by one, the photos I tried to mass up load have not worked.)

I hope this is understandable, I do not want to upload 100++ images one by one when I only need the simple functionality of a gallery. Please feel free to ask me questions.


texts: How do I redirect from a legacy category URL to a new catgory URL using Retour

texts:
I've installed the Retour plugin and have been able to get most of my redirects working, but have now run into a situation where the old site had multi-level category hierarchy eg: /category/category-slug/sub-category-slug url structure and the new site only has a single level eg: /news/category/category-slug

How can I create a Regex to grab the last segment off the url, if there is more than one level of category, to use for my redirect ?

Looks like if there was only one level then the following would do:

/category/* to /news/category/$1

Any tips or ideas ?


texts: Default values of new fields for existing entries

texts:
I added a new SEOmatic field to a section that has around 500 entries. As for any other new fields that you add to a section, the default values are only applied on the entries if you open and save every single one of them once. Shouldn't there be a solution form crafts side? Something like "apply on all existing entries"? Or is there any comfortable solution for that already existing?

... I am thinking about adding a feature request since I was struggling with this several times already. What do you guys think?

Found some other similar questions, but no really easy and satisfying solutions:

Can I add an enabled-by-default lightswitch field to existing entries?


texts: Supersort - Sort multiple variables together

texts:
I'm trying to sort my commerce orders by 2 variables, one being in the order loop, and the second being within the lineitems. I want to order by the lineitem variable first, and THEN the order variable. Something a bit like this:

Order - Group Name
LineItem - Product ID

I want to order by custom product ID asc and then Group Name alphabetically. So it would go a little like this:

ID: 1, GroupName: Aaa
ID: 1, GroupName: Bbb
ID: 2, GroupName: Aab

etc...

The current code I have is this:

{% set orders = craft.orders().limit(null).all() %}
{% set orders = orders|supersort('sortAs', '{{ object.groupName }}') %}

{% for order in orders %}
    {% for item in order.lineItems %}
       {{ item.purchasable.product.customProductId }}
    {% endfor %}
{% endfor %}

Ideally, I'd need to do something along the lines of:

{% set orders = orders|supersort('sortAs', '{{ item.purchasable.product.customProductId }} {{ object.groupName }}') %}

But that obviously doesn't work.


texts: Different templates for different entry types within a section

texts: When specifying the URL and template used to render a section, it's possible to set variable URLs using something like /{postDate.year}/{slug}. Is there any way to accomplish something similar for the entry template, or do all the differences have to be handled within one template that checks for entry type?


texts:
Is there a way to cache content with the (% cache %} tag on a per-user base?

If user A is logged in, his content gets cached. User B logs in, but his content should not interfere with that of User A.


texts: Custom module that can define and have settings referenced (Craft 3)

texts:
I'm currently working on migrating a Craft 2 project which has a bunch of bespoke custom plugins that provided various bits of additional functionality that's tailored to this project only. I've been reading up on the recommended approach in Craft 3 and have understood that modules are better suited in a lot of cases.

However, I've come across a snag with a previous Craft 2 plugin, that basically existed to provide settings that could be referenced in PHP/Twig. This plugin implemented various settings that were defined at config/mycustompluginhandle.php.

I'd like to have the same again but as a module, but it looks like the settings model isn't the same as a plugin and you have to "roll your own" setup for this.

My question is can is a module provide settings via a config/something.php file and can these settings be referenced in other parts of the application i.e. PHP/Twig or another plugin/module? If so, how can I go about doing achieving it?


texts: I'm trying to make a plugin in Craft 3 but want it to be possible to set different settings for each separate site or locale. How would I go about doing this?


texts: Is there a way to detect when a task is finished with js, for example I have a task running I can see the progress bar in the top right corner I would like to attach an event so when the task is done to do some js. Is that possible at this stage of craft. Thank you in advance.


texts:
I am having some problems on integrating Craft Commerce with eWAY.
When I submit the payment form, I get this error:

  Error: [Payment error: EWAY_CARDNAME Required, EWAY_CARDNUMBER Required, Invalid EWAY_CARDEXPIRYMONTH, Invalid EWAY_CARDEXPIRYYEAR, EWAY_CARDCVN Required]

Should the eWAY gateway plugin be converting the form input field names to these eWAY field names?


texts:
Is it possible to set an inline image transform's settings from the output of a Matrix block field?

For example

{% set transform = {
  mode: 'block.imageMode',
  width: block.imageWidth,
  position: 'block.imageFocus'
} %}

Each time I've tried this, the image gives 404. I know the surrounding code works as expected because hard coding the values, the image displays as we'd expect.

This works just fine:

{% set transform = {
  mode: 'crop',
  width: 300,
  quality: 70,
  position: 'center-center'
} %}

EDIT:

Some surrounding code for context

{% for image in block.image %}

{% set transform = {
  mode: block.imageMode,
  width: block.imageWidth,
  quality: 70,
  position: block.focalPoint
} %}

    {% if image.title %}{{ image.title }}{% endif %}

{% endfor %}


texts: Hide navigation from one entry but not others

texts:
I am looking to hide the main navigation for entries that have the lightswitch 'showMainNavigation' disabled. The problem I am facing is when I disable for one entry, the navigation is hidden for all entries. Here is a sample of the code:

{% set mainEntry = craft.entries.slug(craft.app.request.getSegment(1)).one() %}
{% set menuLogo = mainEntry.menuLogo %}
{% set hideMenu = craft.entries.section('mysection').showMainNavigation('not 1').one() %}

{% if hideMenu %}

        {% if menuLogo|length %}

        {% endif %}

{% else %}

        {% if menuLogo|length %}

        {% endif %}
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" onclick="myFunction(this)">

        </button>

list item 1

list item 2

{% endif %}


texts:
I’m getting this error when accessing/writing images. It’s only just come along suddenly after one or a couple of updates.

League\Flysystem\Exception
Impossible to create the root directory
"/Users/username/Sites/project-name/craft/web/images/folder". mkdir():
Permission denied

Running Nitro with Multipass 1.5
Multipassd has all Full Disk Access (but had to add this manually from Application Services)
Craft CMS 3.5.16
MacOS Catalina 10.15.7
Composer version 2.0.8
Unable to change file permissions in Finder/Transmit etc
Not new installs
Unable to load an image through CP. Same message as above

Nitro running other simpler site fine, so no problems there.
At a loss, any site running locally that needs images will fail to load, but /admin runs all fine.
Thanks :)


texts: Running Craft with Docker (or something similar)

texts:
Has anyone had success with setting up Craft using Docker?

I've stumbled across some Dockerfiles for WordPress and other CMS's but couldn't find much in the way of Craft. I'll be exploring this a bit myself over the next week, but was hoping some people in the community may have a few good pointers or tips or even cautions.

To elaborate, I'm looking for alternatives to MAMP as well, or other development environment tools for working with Craft.


texts: With Matrix blocks how can i get the column names

texts:
From a craft matrix block how do i get the field names when no data has yet been entered?

i can write:

$o_matrix_block->getContent()->getAttributeConfigs();

this will give me an array:

 Array
                    (
                        [id] => Array
                            (
                                [maxLength] => 11
                                [min] => -2147483648
                                [max] => 2147483647
                                [decimals] => 0
                                [type] => number
                                [unsigned] =>
                                [length] => 10
                                [column] => integer
                            )

                        [elementId] => Array
                            (
                                [maxLength] => 11
                                [min] => -2147483648
                                [max] => 2147483647
                                [decimals] => 0
                                [type] => number
                                [unsigned] =>
                                [length] => 10
                                [column] => integer
                            )

                        [locale] => Array
                            (
                                [column] => locale
                                [default] => en_gb
                                [type] => locale
                            )

                        [title] => Array
                            (
                                [required] =>
                                [maxLength] => 255
                                [label] => Title
                                [type] => string
                            )

but I only get the array, when I have entered data.

with out getcontent() but the array elements are wrong

Pls help!

:)


texts: Can an integer be formatted as a telephone number using Twig?

texts:
Can an integer be formatted as a telephone number using Twig filters or other methods?

I have looked at the 'number_format' filter but it seems to be limited to controlling the number of decimals and how to delimited thousands.

Example; Integer variable from cms '20304050', output to HTML in twig like this: '20 30 40 50'.


texts: Array from matrix fields without quotations

texts:
I am trying to create an array bodyBlocks by looping through all of my matrix fields called blockTextContent:

$bodyBlocks = [];
foreach ($entry->getFieldValue('pageBuilder')->all() as $block){
    switch ($block->type->handle) {
        case 'blockText':
            $bodyBlocks[] = $block->blockTextContent;
            break;
        }
    }

// Begin defining the response data for this entry
$data = [
    'title' => $entry->title,
    'slug' => $entry->url,
    'status' => $entry->status,
    'textArea' => $bodyBlocks
];

The JSON response is as below, focusing on the textArea line.

"title": "Title Here",
"slug": "slug-here",
"status": "live",
"textArea": [
    "
Text from first 1st block
",
    "
Text from first 2nd block
",
    "
Text from first 3rd block
",
],
"heroBanner": "img.jpg",

The above is working as expected, cool. BUT I'd like the response to appear as below. Merging that matrix field in to one line in textArea, so without the separating quotation marks and surrounding square brackets [ ]?

My desired response would look like this in the end:

"title": "Title Here",
"slug": "slug-here",
"status": "live",
"textArea": "
Text from first 1st block

Text from first 2nd block

Text from first 3rd block
",
"heroBanner": "img.jpg",

Thanks!


texts: How do I get rid of whitespace when rendering without touching template indentations?

texts:
I have the following code.

{% spaceless %}
{% for date in entry.d_date %}
    {% if date.showMonth == 1 %}
    {{ date.date.month }}-
    {% endif %}
    {% if date.showDate == 1 %}
    {{ date.date.day }}-
    {% endif %}
    {{ date.date.year }}
{% endfor %}
{% endspaceless %}

Which outputs 1- 1- 2014

Is there anyway to get rid of the whitespace without touching the indentation? I've used {spaceless} but it's not working.


texts: Use alias for site url based on root url defined as env var?

texts:
I was wondering if the following setup is a good practice.

In my .env file I defined a single rootUrl var which contains the site root url like this:

ROOT_URL="https://www.mydomain.test"

In the general.php config file i've created an alias (@rootUrl) that contains the ROOT_URL env var value:

'aliases' => [
        '@rootUrl' => getenv('ROOT_URL'),
    ],

Then I define my craft sites as following (multilingual site), each site BASE URL is constructed with the rootUrl and a language:

Advantages

You don't have to define every site (language) in the code, languages are managed through the cms (in case of multisite setup, you should define a ROOT_URL for every site).
the @rootUrl alias can be used as part of the resource path in the templates.

Disadvantages

Could this also resolve in a caching issue (like the @web alias)?
...

Does this logic makes sense or is it generally a bad idea to use aliases for the site BASE URL setting?

Thanks in advance


texts: Setting template mode to CP doesn't let me load plugin templates

texts:
Setting template mode to CP with craft()->templates->setTemplateMode(TemplateMode::CP) only lets me load templates from app/templates.

If i load app/templates/entries/_fields.html and I use custom fields in the entry, this will attempt to load those edit templates from plugins/{pluginName}/templates and I receive an error because the templates could not be found in app/templates.

Shouldn't templateMode -> CP behave more like proper CP and not just set a single load path?


texts: pass block into embed and forward to another embed?

texts:
I'm trying to achieve some modularity using embeds, but with the possiblity to extend/inject customizations from the including template.

Consider the following scenario:

Have a modular partial which contains a form, say form.twig
I want the ability to add new form fields at the end of the form, but using the otherwise common form.twig, so I add a {% block form_extension %} in form.twig

I have another page template, that includes/embed that partial, say page.twig. Now, this works, I just add a block when embedding, and it gets injected.

But, I also have another modular partial, say partial_with_form.twig, that embeds form.twig. And I want to be able to define the form_extension block, when embedding partial_with_form.

Is this even possible? I have tried with parent() and block(), but none of them can give me the content of the supplied block unless I specify the targeting block in partial_with_form. But then it will be outputted there...


texts: How to insert widgets in Rich Text field

texts:
I want to insert widgets in arbitrary positions in one of my rich text fields. A good example would be a contact form inserted in the middle of the content. These widgets would be ad units, forms and similar dynamically rendered templates.

I know about the widget plugin for Redactor, but this is only suitable for static HTML. I need something a bit closer to an {% include %} tag.

How would you approach this problem?

I considered using WordPress-like [insert-widget-here] tags, or perhaps iFrames, but I'd prefer a more elegant solution.


texts: How to access a freeform field object's properties from an event

texts:
I am trying to get the value of a field from a freeform event.  Specifically I'm trying to see if a particular checkbox is in a form submission.

craft()->on(
    "freeform_submissions.onBeforeSave",
    function (Event $event) {
        $submission = $event->params["model"];
        $field = $submission['fieldMetadata']['checkbox_handle'];

This works to this point.  I see if I do Craft:dd($field); I have a checkboxField object. But from here on I can't get any info about that field.

        $id = $field->id; // or:
        $handle = $field->handle; // and any other properties

This throws: Fatal error: Cannot access protected property Solspace\Freeform\Library\Composer\Components\Fields\CheckboxField::$id.

If I try:

        $id = $field['id'];

I get: Fatal error: Cannot use object of type Solspace\Freeform\Library\Composer\Components\Fields\CheckboxField as array

The properties and methods are listed at: https://solspace.com/craft/freeform/docs/field/, but I can't access the properties.  I can call the render() method which works and that outputs html.  I'm sure its something obvious, but I'm missing it.


texts: Craft admin twig templates broken somehow

texts:
I am a front end designer building my site locally. This is the first time I've built in Craft and things have been coming along fine but now I'm getting the following error on every craft admin page and I'm not sure what's happened or how to fix it.

  Twig\Error\SyntaxError: The block 'content' has already been defined
  line 256. in
  /Users/jinora/sites/janahoffmann/_repo/v4/vendor/craftcms/cms/src/templates/_layouts/cp.html:274

The front end of the site seems fine and still loads all the templates and entries.

I had just changed an asset field to use a different folder and they weren't loading on the front end so I went into utilities and tried clearing the database cache and that's when the admin stopped working.

I had recently named a block in my templates 'content' but it had been working fine for a little while and I tried renaming the block but that didn't fix anything.

I had noticed that there was a new craft update but hadn't got to it before so I tried using terminal to update it as per this docs page (since I can't get to the control panel update) https://docs.craftcms.com/v3/updating.html#updating-from-the-control-panel. Weirdly it says the following...

Craft isn’t installed yet!

  Fetching available updates ... done You’re all up-to-date!

I took back ups and then tried clearing the storage/runtime/cache and compiled_templates folders, I restarted mamp and closed the browser but still nothing. I haven't messed around with anything outside the web or templates folder before this so I'm completely stumped as to what's happened and how to fix it.

Can anyone point me in the right direction?


texts:
I want to display the current entry's index - like in this post Get entry index.

However my entries are in a structure section type not a channel, so they are not ordered by date.

Is is possible to edit the solution (below) from the above post so that it is not sorting the entries by date but rather retaining the custom order of the structure?

{# Get this entry + all entries posted before it #}
{% set postDateParam = '<= ' ~ entry.postDate|date('c') %}
{% set entryIds = craft.entries.section('news')
  .order('postDate asc').postDate(postDateParam).ids() %}

{# Count them #}
{% set position = entryIds|length %}

{{ position }}


texts:
This complex query makes the server cpu run at 100%.

{% set entries = craft.entries({
      section: sectionParam,
      search: searchParam,
      relatedTo: relatedToParams,
      condition: conditionParam,
      price: [
          'and',
          '>= ' ~ pricesParam|split(';')[0],
          '<= ' ~ pricesParam|split(';')[1]
      ],
      priceOffer: [
          'and',
          '>= ' ~ pricesParam|split(';')[0],
          '<= ' ~ pricesParam|split(';')[1]
      ],
      specsMtplm: weightParam,
      specInternalLengthFeet: lengthParam,
      priceOffer: '',
      specsBerthSleeps: [
          'and',
          '>= ' ~ berthsParam|split(';')[0],
          '<= ' ~ berthsParam|split(';')[1]
      ],
      spectransmission: transParam,
      seatbelts: seatbeltsParam

}).order('dateCreated desc').limit(null) %}

How can I optimise this twig so it doesn't kill the server each time it runs?


texts:
So, I've created a plugin which has to send dynamic data to an entry in the control panel, using a custom field type

I get an error in the ajax call, saying that the URL to which I'm posting is not found. I've debugged this and the URL generated is the right one, I've tried posting to it from other places and it works just fine

This is what I have so far

The custom field

public function getInputHtml($name, $value)
{

    craft()->templates->includeJsResource('baseinstagram/js/pullajax.js');

    return craft()->templates->render('baseinstagram/input/choosetag', array(
        'name'  => $name,
        'value' => $value
    ));
}

The ajax call

$(document).ready(function () {

var url = Craft.getActionUrl('baseinstagram/main/testy');

$('.pullme').click(function () {
    $.ajax({
        method : 'POST',
        url : url,
        success : function () {
            console.log('ok');
        },
        error : function() {
            console.log('nope');
        }
    });
});

});

the controller

public function actionTesty() {
    $this->requireAjaxRequest();

    $this->returnJson('heyeyeye');

}


texts:
Now I have a "gallery image" field which allows users to upload multiple images, and some "single-upload image field" in matrix block.

For "single-upload image field", I want to force users to choose images only from the "gallery image" field.

To do that, I want to create a custom asset source called "gallery image". So with this source selected, I can limit the source of "single-upload image field".

Any idea to achieve this? Thanks!


texts:
I have a job board running on Craft. We're "auto expiring" the posts from listing pages based on the post date.

However, I want to redirect the actual entry page to either a 'this job has expired' page in cases where some one is linking from an external site.

Is that possible?


texts:
I have a question. How can I output the Childs from a Neo (Neo Plugin) Block?

With this code, i get the output for all level 1 blocks but i don't get a output for the deeper levels.

And how can I handle different child templates for the Output?

My idea is to have a switch with different case for the level 2 output. Because i've different child block options.

{% for block in entry.MatrixNeo.level(1) %}
    {% switch block.type.handle %}

        {% case 'title' %}

{{ block.mainTitle }}

        {% case 'boxes' %}

{{ block.mainTitle }}

            {% for item in block.children %}
                {% switch block.type.handle %}

                    {% case 'box' %}

{{ block.mainTitle }}

                        {% case 'image' %}

{{ block.mainTitle }}

                {% endswitch %}
            {% endfor %}

    {% endswitch %}
{% endfor %}

Can somebody help me out, please?

=====================

UPDATE

Now my code works fine but i've a new questione:

How can i output a real Matix-Field in a child element (level 2 in Neo).

My Code:

{% nav block in entry.myField.level(1) %}
    {% switch block.type.handle %}
        {% case 'title' %}
            <hgroup>

{{ block.mainTitle }}

{{ block.subTitle }}

            </hgroup>

        {% case 'intro' %}

                {% for item in block.children %}
                    {% include "_includes/elements/" ~ item.type %}
                {% endfor %}

    {% endswitch %}
{% endnav %}

The child Code:

{{ item.mainTitle }}

    {% for button in block.myButton %}
        {% switch button.type %}
            {% case 'buttonIntern' %}
                {{ button.linkText }}

            {% case 'buttonExtern' %}
                {{ button.linkExtern }}

        {% endswitch %}
    {% endfor %}


texts: Recovering (or creating a new) admin account

texts:
Our developer hasn't been able to recover his password for the account he used to setup the site, and now he's non-responsive. The site is on my server and I have full access, but his account is the only one we setup.

We're not able to add new companies until we can either recover the account or setup a new one.


texts: Environment variable doesn't work in Assets field settings

texts:
I created an environment variable (in config/general.php) called {baseAssetPath} which contains the server path to the folder where all my assets are stored. This makes it easier to populate the Path field in Assets settings.

However, this variable does not appear to work to configure the Upload Location when setting up an Assets field. Now, when I attempt to add an asset, or edit an existing entry, I get the following error.

Internal Server Error

Craft\EntryModel and its behaviors do not
have a method or closure named
"baseAssetPath".

Is Upload Location looking for a server path or a URL path?

If it's looking for a server path, why doesn't my {baseAssetPath} variable work here?


texts: Pulling categorized entries in a category loop

texts:
I am trying to pull channel entries and display them using a loop. These entries would then be organized by the category they are assigned to based on a categoryfield a user selects when creating the entry. Below is the code I am beginning with.

{% set category = entry.myCategoriesField.first() %}
{% if category %}
 {% for car in craft.entries.section('category')%}
  **Might need a set option here for entries??**

  {{car.Title}}
  {{car.carDescription}}

 {%endfor%}
{% endif %}

Should look like:

Car

Prius: {{Description}}

Truck

Ram {{Description}}
Silverado{{Description}}

SUV

Suburban {{Description}}
Escape {{Description}}

Any thoughts or direction would be helpful.

I have looked into the following code but don't think it would work the way I want to.

{% set category = entry.myCategoriesField.first() %}
{% if category %}
    ...
{% endif %}


texts: Can I add information to a CP new entries page?

texts:
I would like to add a google map in an entry edit page for certain entry types.

I already have a plugin started to go and grab the lat and long for the entered address.  What I'm now trying to achieve is to add the map to the admin page. I'd like to put it in the right pane.

I have looked at hookRegisterCpRoutes() but I don't think it's possible to override pre-existing routes.

Is their a way to achieve my goal or my plugin should be taking care of the entire entry type instead ?


texts: Render Field from FieldHandler in FreeForm Craft CMS

texts:
Can we render some particular field from our FreeForm plugin ?

If yes, how can we achieve it ?


texts: "Conditional" field layout - hiding or showing fields based on another field

texts:
is it somehow possible to conditionally show or hide fields in the entry editor based on the value of another previously entered field?

An example of this use would be:

A section has Lightswitch field "hasVideo"
User is populating a new entry for this section and sets "hasVideo" to the value of choice.
If user sets hasVideo to true, show a text field "productVideo" so that the user can set a link to a youtube video, but hide assets field "productImage".
If user sets hasVideo to false, how Assets field "productImage" so that the user can upload an image, but hide "productVideo" field.

This would really help from a usability perspective since the client will only be shown the fields that need to be filled based on what was filled earlier on - creating a sort of entry creation "wizard".

Naturally there might be an alternative route to achieve the same level of usability that I'm missing.

Thanks in advance!


texts: Is it possible to target a fieldtype by it's Type name, rather than the handle name?

texts:
I've created an Asset Source and assigned my own field via the field layout.

Then, I created an Assets Field to display a single image on a page. Using my plugins twig extension I can query the image object like so:

{{ entry.featuredImage.first()|myTwigExt }}

Now, in the Twig extension I want to target the first instance of my field using its Type, not the Handle.

The reason for this is because the handle can be defined by the user, but the type name is always the same. I want to avoid the need to parse in the field handle along with the Twig Extension like this:

{{ entry.featuredImage.first()|myTwigExt('notThis') }}

If this is even possible, my ideal situation would have my Twig Extension looking something like this:

  public function getFilters() {
    return array(
      'myTwigExt' => new Twig_Filter_Method($this, 'myTwigExtension'),
    );
  }

  public function myTwigExtension($image, $param) {
   if ( $image->type('myCustomField') ) {
     // YAY!
     return $image->type('myCustomField')->someDataFromMyField;
   }

   if ( $image->$param ) {
     // "Boo!";
     return $image->$param->someDataFromMyField;
   }
  }

This is the cleanest way I can ask this question. Without going into too much detail about my plugin (which would just confuse the situation more).


texts: My plugin's custom fields don't show values when entry saved as draft

texts:
When entries with plugins custom fields are saved as a draft, the data previously entered in the custom field is not visible. It is saved in the database but doesn't show in the edit screen.  The data will show in the fields when the entry is published.

  {{ forms.dateTimeField({
    label: "Start Date"|t,
    instructions: "When should the event start?"|t,
    id: 'eventStartDate',
    name: name~'[startDate]',
    value: (fieldData ? fieldData.startDate : null),
    errors:''
  }) }}
  {{ forms.dateTimeField({
    label: "End Date"|t,
    instructions: "When should the event end?"|t,
    id: 'eventEndDate',
    name: name~'[endDate]',
    value: (fieldData ? fieldData.endDate : null),
    errors: ''
  }) }}

Is there a different way to output the data to the template so it shows in both?


texts: How do I make it required to enter password when changing user data?

texts:
Is it possible to enforce users to enter their password when changing their data?
For example when changing their phone number.

Thanks in advance


texts: Can't dynamically add value to hidden input Sprout field

texts:
I'm trying to add a hidden input with Sprout forms and Sprout fields but I can't dynamically add a value to the input attribute.

I have a custom form template in craft/templates/_forms/field.html in which I have the following code for the hidden field:

{%- set name = field.handle is defined ? field.handle : null %}
<input type="hidden" name="{{ name }}" value="{{ settings.value }}">

This now returns whatever value I put into the 'Hidden Field Value' input in the form builder in Craft, but if I put any dynamic data in there, e.g. {{ craft.request.path }} (which is also the placeholder text), I get the same literal string back: "{{ craft.request.path }}". I've also tried with single braces, as I read that this might be the correct syntax, but I get the same result.

Eventually, I am wanting to set the value to {{ entry.title }}. I read that I need to add this to my template to be able to access non-global variables {% do craft.sproutForms.addFieldVariables({ entry: entry }) %} - does this go in the entry template just before the form, or in the form template. I get an error saying Variable "entry" does not exist if I put it in the form template so I'm guessing it goes in the entry template.


texts: Where are all these columns coming from on the Entries in happy-lagger.test project?

texts:
I just started looking around the example project happy-lager, and I realised that on the Entries there's a bunch of columns displayed that I don't see on my company project (URI, Service Icon and some others in different Entries, such as background colour or image thumbnails). I didn't know this was possible, but it's great. How are those set?

FYI: Our project was updated from Craft 2, I don't know if this might be related.


texts:
Can this be done? I have a section called Bookings. I have 2 user groups A and B.

I would like both groups to have access to the section (bookings) but for some of the entries in the section, I would like to exclude one of the groups. Giving access to only A or B.

thanks.


texts:
I'm trying to get my head round how Craft Commerce manages product options. My Product has the following (multiple) options.

Material Type
Distance between design
No. of designs per metre
No. of meters (selecting this changes the price, so 1 metre is £100 and 2 metres is 200 etc)

The options can be set independent of each other.
Distance and No. of Designs will have set ranges the customer can choose from.
As this is just one product that effectively gets customised by the options there is no stock level.

Question One: Is multiple options on one product possible?

Question Two: Do I need to create variants for each option - how if so?

Question Three: Do I need multiple products based on the number of Metres (which changes the price)? Ideally I'd like one product that gets adjusted on the options selected. Is that possible?


texts:
I've got a client project which utilizes the Users section of craft pretty heavily. I am trying to figure out if it is possible in vanilla craft to move a user from one group to another say, from the 'employee' group to the 'manager' group. I have seen some code to do it in a custom controller action in a few other posts on here, but I'd rather avoid creating a custom plugin for this if possible.

So is this possible? Thanks!


texts:
I am running Craft locally using default/update Laravel Homestead/Vagrant box.

Image Transforms are returning the CP resources URL 404 error outlined in this related question:
Image transforms returning cpresources url

I've confirmed that my host and vagrant box have the correct permissions
I've cleared cache and reindexed assets
I've tried the 'generateTransformsBeforePageLoad' => true,

I still receive the error: Failed to load resource: the server responded with a status of 404 (Not Found)


texts: Is it possible to display another column in Entries type field?

texts: I would love to be able to show another column inside Entries type field. Specifically, Image field. Basically,the same functionality as on the Entries list. Is there a plugin or another way of implementing this.


texts: Is there a way to return asset data along with entry data?

texts:
I'm using the Element API plugin to return data from an entry that also contains an image asset. Is there a way to combine the two so I can get the asset URL alongside the entry fields?

Attached below is an approximation of my line of thinking.

        'elementType' => 'Entry',
        'criteria' => ['section' => 'wax'],

        'transformer' => function(EntryModel $entry) {
            return [
                'excerpt' => $entry->excerpt,
                'heroImage' => $asset->heroImage.url // Something like this?
            ];


texts: How to make URLs translatable in Craft 3

texts: I am trying to make the URLs translatable according to the language selected for the site.


texts: Craft sometimes takes several minutes to respond to a request

texts:
I have a pretty simple Craft site running a Digital Ocean Ubuntu droplet and for some reason it can sometimes take several minutes to save an entry.

I think this might be something to do with sessions as, when it happens, the site stops responding completely for that browser unless I quit and re-open it. Whilst it is happening, accessing the website via another browser works fine. There's nothing in the phperrors.log or the craft.log that even relate to the time the problem happens but there's something in the Application Logs that seem relevant.

Here's a sample of the 'Profiling Summary Report' where you can see it took 300s to respond but none of the queries takes anything other than milliseconds: http://pastebin.com/pbf7bj2e

The interesting bit is is the Application Log where you can see the timestamps jump from 13:00 to 13:05 on line 58:

http://pastebin.com/gdCgTUSC

What is happening there that took 5 minutes?


texts: Element Meta Image (OG/Twitter) Wiped On Save

texts:
I'm giving Sprout SEO a try specifically for the Facebook OG and Twitter card handling - however specifically in these two cases, when I choose an image, it gets wiped. No messages or errors.

I've tried both already uploaded images and newly uploaded images.

This is only the case when editing an Element, not a Section.

Anyone else had this issue?

Craft CMS 2.6.2903 | Sprout SEO 3.2.0


texts:
Is there any way to use a macro in twig to define a variable outside that macro?

For example, say you want to use a macro to set a variable that stores an entry's parent (I know you can do this much simply, but I have my reasons to want to do it like this), I would intuitively want to do something like this:

{% macro getParentEntry(thisEntry) %}

    {% import _self as self %}

    {% if thisEntry.parent|length %}

        {% set parent = thisEntry %}

    {% else %}

        {% set parent = false %}

    {% endif %}

{% endmacro %}

{% import _self as self %}
{% set parent = self.getParentEntry( entry ) %}

But this clearly isn't quite right.

Am I missing something, or is this just not possible. (I couldn't find any mention of anything like this in the twig documentation.)

Many thanks!


texts: linking to staff page, how to setup entry

texts:
I am fairly new to Craft and I am hoping someone can help point me in the right direction so I am not having to do double the work or have to learn the hard way that there is an easier way.

I am trying to get my head around how I can tie pages together. I am creating a page for videos from speakers but I want the speakers names to be linked back to their staff page.

How do I create an entry that will allow users to select a staff member?

I have already created a staff entry page, that allows all the information to be populated for the staff member. Should that be a categories page instead to allow me to have a the user select the staff member (category) that did the talk for the video? Or is there another way to allow the user to select a field of staff members?

Thanks for the help!


texts: Validating Date of Birth format from a form field value

texts:
I'm working a on website project which includes a web form which asks for various personal details, one of the fields on the form is Date of Birth.

The form is being validated by a custom plugin which is using models for validation.

Currently the AttributeType for the Date Of Birth field is defined as AttributeType::DateTime, so bad values just get removed during POST, however it would be nice to try and catch values that fail a date format validation of dd/MM/yyyy so the user can correct it, otherwise the field value will simply be discarded and user will be unaware of this.

What is best way to check and catch that the Date Of Birth field value isn't in the required format? I want avoid any regex related parsing as I'm sure there are better ways to examine the format using other PHP date related functions.


texts: Assets folder first level open by default

texts: Is there any way to make the Assets folder also show the first sub folder level by default, like in the attached screenshot?


texts: Is it possible to route to www.site.com/username?

texts:
So what I'd like is:

If URI would look like {username}, load _thisTemplate.

Couldn't find the way without solid point like author ID.


texts: White space added to start of template's

texts:
There is white space being added to the start of my templates.

This isn't really an issue but because its happening to an RSS template that is breaking the feed and causing it to not validate.

When I edit the template in my text editor the white space is not there, so I think it is Craft adding when when rendering the template?

My code looks like this, you can see on line 1 there are no spaces before I declare the XML version. <?xml

However, on the front end it is rendering like so: I have highlighted the space in blue.

Because of this, the RSS template is not validating and is causing my feed to break.

This started recently, I am not sure if it is linked to a recent Craft update but it started happening around the same time.

Craft v3.0.26.1

Any help appreciated :) Thanks


texts:
I can use {product.slug} for generating Auto SKU but does anyone know how to use the Product ID

Using SKU{product.id} the create product form won't submit because no SKU is generated. I think it might be because there's an error there but I can't see anything in the logs.

Using just SKU{id} allows the form to submit but the result is just "SKU", so it isn't fetching the product id.

I've tried ID and id in both cases.

I'm sure this should work. Any ideas?


texts: Show a list of pages but hide the current page from the list

texts:
My setup

I'd like to show a navigation menu listing all my page entries.
In my layout file, I include a template for the navigation:

_layout.twig:

        {% include "_includes/navigation.twig" %}

        {% block content %}
        {% endblock %}

The current page is shown in the content block.

My question

Is there a way to globally access the currently viewed page, from inside the navigation.twig template. That way I could do:

{% set currentPageId = SOME_COOL_GLOBAL_FUNCTION %}
{% set pages = craft.entries.section('pages').id('not ' ~ currentPageId).all() %}

        {% for page in pages %}

{{ page.getLink() }}

        {% endfor %}


texts: Bug with non-ascii characters, quotes and OR operator in search?

texts:
There seems to be a bug when I combine non-ascii characters, quotes and the OR operator when searching.

All of these queries work ok:

"pølser"
"pålegg"
pølser OR pålegg
"egg" OR "spekemat"

but

"pølser" OR "pålegg"

always returns no result.

The search form uses roughly this code:

{% set searchTerm = craft.request.getParam('search') %}

{% set entries = craft.entries %}

... entries is optionally limited to a single section here, but it makes no difference here ...

{% set entries = entries.search(searchTerm) %}

Any ideas?

Cheers!

(cross-posted from google+ group as I only just found out about the stack-exchange)

(edit to add code sample)


texts: Title Format - Auto Generation via linked entry

texts:
Finally hopping back into Craft to finish a large project, and am loving so many of the new features added! One thing I am using extensively is the Title Format feature. For one of my entry types, my Title Format field looks like so:

{songTitle} - {{ performedWith.entry.title }}

performedWith is the name of a field that links to an entry. I assumed I could do entry.title to pull the title from the linked entry, but it is simply showing up blank. Any ideas? Thanks!


texts: Compare custom-field value of entry to registration-form field value before saving user

texts:
Whoo, that title is a mouthful...

I'm trying to check against a unique school "code" that an athlete has to input to register with a team. The code is different based on what team they are trying to join (referenced in a segment of registration page URL). I have no idea what I'm doing when it comes to PHP or plugins but I hope I'm on the right track. I have no idea how to test what values my variables have.

I've essentially copied the user/SaveUser controller into my own plugin (I have to place user in Athlete user group & related the specific team entry to user, hence custom plugin) and placed snippet below right before the if (craft()->users->saveUser($user)) line.

$teamName = craft()->request->getPost('fields.teamName');
//Get team name, set in hidden input in form, which was grabbed from segment

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'teams';
$criteria->title   = $teamName;
$criteria->limit   = 1;
$entry = $criteria->first();
//Find the Team entry in my 'teams' section

$schoolCode = $entry->schoolCode;
//Place value of schoolCode field in variable

$codeInput = craft()->request->getPost('fields.schoolCode');
//Grab user's input

if ($schoolCode == $codeInput)
{
    craft()->users->saveUser($user)
}

This is, of course, not working. I'm not getting any errors either.

Am I anywhere close to doing this right?


texts: Is it still possible to install all of Craft 3 in a public folder? Like you could with Craft 2. If it is, how do I do it?


texts:
I thought this would be easy.  I cut and pasted code that works from the Mijingo Happy Lager tutorial site. But, I keep getting the template error below.

My code...

{% paginate craft.entries.section('posts').limit(8) as postEntries %}

    {% for post in postEntries %}

{{ post.title}}

{{ post.postDate | date('F d, Y') }}

    {% endfor %}

            {% if paginate.prevUrl %}

Previous Page

            {% endif %}

            {% for page, url in paginate.getPreviousUrls(5) %}

{{ page }}

            {% endfor %}

{{ paginate.currentPage }}

            {% for page, url in paginate.getNextUrls(5) %}

{{ page }}

            {% endfor %}

            {% if paginate.nextUrl %}

Next Page

            {% endif %}

{% endpaginate %}

The error message...

  Neither the property "getPreviousUrls" nor one of the methods "getPreviousUrls()", "getgetPreviousUrls()"/"isgetPreviousUrls()" or "__call()" exist and have public access in class "Craft\PaginateVariable"

What am I forgetting?


texts: Super Table fields in Matrix blocks not automatically propagating content across sites

texts:
Please bear with me as I try to explain what's going on. Feel free to ask for more details if needed.

Simply put, Super Table fields in Matrix blocks are giving me trouble for multi-site.

I am running Craft 3.4.2, and the latest version of Super Table, 2.4.9.

I rolled back to Craft 3.4.1 and Super Table to 2.4.5, and experienced the same problems below.

Expected Behavior:
When I add a new site(language), the content that is already in the default site will propagate to the fields in the new site when the fields are properly configured to either 'translate for each site' or 'not translatable' and/or 'save blocks to all sites the owner element is saved in'.

Actual Behavior:
All fields except Super Table fields inside Matrix blocks propagate to the new sites automatically.

Also note that after new sites are added, if I change one of these Super Table fields inside a Matrix block in the default site/language and resave the entry, then the  content will propagate to the other sites/languages, but content propagation does not happen automatically after adding the new site, as I expect it should, and as happens in other fields.

Questions:
1.) How do I figure out if this is a Super Table bug, or a Craft bug? (I have not seen similar issues on the Super Table github page)
2.) Is anyone else experiencing this?
3.) How can I fix it?(the most important question:) )

Thank you in advance whoever can guide me in this, or point me in the right direction.


texts: Proper order of multi-environment config

texts:
When using a multi-environment config, Craft will select which settings to use based on a partial string match of the server name.

Given the following example, does "dev.mywebsite.com" need to be first or last? Clearly it contains "mywebsite.com" within it, so the order is relevant.

return array(
    // All environments
    '*' => array(
        'tablePrefix' => 'craft',
    ),
    // Production
    'mywebsite.com' => array(
        'server'   => 'localhost',
        'user'     => 'xxxxxxxx',
        'password' => 'xxxxxxxx',
        'database' => 'prod_mywebsite',
    ),
    // Development
    'dev.mywebsite.com' => array(
        'server'   => 'localhost',
        'user'     => 'xxxxxxxx',
        'password' => 'xxxxxxxx',
        'database' => 'dev_mywebsite',
    ),
);


texts: Move an asset to another volume with volume specific OptimizedImages Field and on the entry a volume restricted Asset Field

texts:
I have three volumes: content, hero and overview.
Each volume has his specific OptimizedImages Field(s).
Asset Fields are restricted to its specific source volume.

For example: A Super Table Field named hero that contains an Asset Field, which is restricted to the hero source volume.

If an asset is set as a hero image and the client would move the asset in the asset manager to a different volume, two problems appear.

On the entry, the image is set as hero image although the field doesn't allow an asset from an other source.
In the template you can't call the hero OptimizedImages Field on the asset.

Even if you provide multiple conditionals in the template and some kind of fallback image, the client still sees the image set in the Craft CMS backend.

Any suggestions how to solve this problem without putting everything in one volume?


texts: Getting custom user attributes in a service, they return NULL

texts:
I'm building a service where a few user attributes (category fields) are needed and have to be compared against an entry.

However, when I get the current user and try to load these attributes, they show as NULL. They are filled in at the user's profile, so they shouldn't be NULL.

Below is the code I have used to get try and get the attributes values.

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

Some values are filled out, like the custom field for postal code and phone number. However those category fields are all NULL.


texts: What's the best way to paginate through entries from an entries field type?

texts:
I have an entries field type associated with a structure section page. This displays the entries on this page in a particular order. When you click an entry link ti will take you to  a detailed page for more information about that entry. What I'd like to be able to do is paginate through these entries in the order set in the entries field, not just paginate through the entries in asc/desc or alphabetical order as would happen if I just paginated through the channel section that stores the entries.

I tried straight forward pagination as detailed in the documentation but two problems occurred. First the pagination links were created with proper beginning end and number but when clicking through them you remained on the same entry. Second, a pagination URI was appended to the URL which I don't want.

Is pagination even the proper approach to this problem or is there a better solution?


texts: Task "Resaving all localizable elements" is stuck when adding new new locale

texts:
I'm trying to add a new locale, but the task "Resaving all localizable elements" is stuck and the new locale is not being added to content.
Even after restarting the task.

There are no errors in the log file.


texts: What Might Be Causing This Serialization Error?

texts:
Craft Pro 3.0.7Notifications Plugin 1.0.6PHP 7.0

In trying to send notifications for new entries that have a checkbox field, we get this error in the logs:

  2018-05-14 09:19:32
  [192.168.10.1][1][-][error][UnexpectedValueException]
  UnexpectedValueException: Error at offset 0 of 2 bytes in
  /home/path/to/vendor/yiisoft/yii2-queue/src/serializers/PhpSerializer.php:32

This manifests as the notification getting stuck in queue, never releasing, always showing progress bar.

Removing only the checkbox field from this section, the notifications work as expected without any errors.

From what I read, serialization errors may result from encoding problems.

What else can I try to resolve this? Where else can I look?


texts:
I have a custom field that allows customers to order a sample from a list of all products. It also allows a custom value to be entered for a custom color. I conditionally show/hide the fields with javascript and all the options are available on one product type. This works great except for one thing. On the admin emails it shows every option even if nothing was filled out. I have the labels set to only show if there is a value but they still output.

Here is the product type code:

    <select name="purchasableId">
        <option>Please Select Sample Type</option>
        {% for purchasable in product.variants %}
        <option {% if purchasable.stock <= 0 and purchasable.hasUnlimitedStock == false %}disabled {% endif %}
                value="{{ purchasable.id }}">{{ purchasable.description }} {{ purchasable.price|commerceCurrency(cart.currency) }}</option>
        {% endfor %}
    </select>

    {# pattern #}
    <select name="options[pattern3a]">
      <option value="">Select Wallpaper Sample 1</option>
      {% for product in craft.products.type('wallpaper').all() %}
      <option value="Sample - {{ product.title }}">{{ product.title }} </option>
      {% endfor %}
    </select>
   <select name="options[pattern3b]">
      <option value="">Select Wallpaper Sample 1</option>
      {% for product in craft.products.type('wallpaper').all() %}
      <option value="Sample - {{ product.title }}">{{ product.title }} </option>
      {% endfor %}
    </select>

    {# custom color #}

Enter Your Custom Color Options

    <input type="text" name="options[customColor3a]" placeholder="Custom Color 1" value="">

And this is what I use on the admin emails:

{% for item in order.lineItems %}
{% if item.purchasable.product.type.hasVariants %}
...
{{ item.description }}
{% if item.options.pattern | length %}
    {{ item.options.pattern }} |
{% endif %}

{% if item.options.customColor3a is defined %} |
    Custom Color 1: {{ item.options.customColor3a }}
{% endif %}
{% if item.options.customColor3b is defined %} |
    Custom Color 2: {{ item.options.customColor3b }}
{% endif %}
...

And finally, on the emails it looks like this:

Sample 1 - Product Name,
Custom Color 1: Green | Custom Color 2:

So I basically just want to hide the labels if nothing was selected. In the case above just not output "Custom Color 2". Any help would be appreciated!


texts: Charge Pro not sending Subscription Emails

texts:
So I've actually created a fix for this, but it's a bit complicated. Wanted to share in case anyone else runs into this problem.

Working in Craft 2.6.2954 and Charge Pro 2.18

When creating new subscriptions, the emails were not being sent properly. I checked the charge logs in the charge plugin and it was giving me an error of "Failed to find email with the handle : Welcome Email". I figured out that "Welcome Email" was the correct name of my email, but it wasn't the handle, which is why it wasn't being found. I created a new function in the Charge_EmailService.php file called _getEmailModelByName, you can see it here:

private function _getEmailModelByName($handle = null)
{
    if ($handle) {
        $emailRecord = Charge_EmailRecord::model()->findByAttributes(
            ['name' => $handle]);

        if (!$emailRecord) {
            return false;
        }

        $model = Charge_EmailModel::populateModel($emailRecord);

        return $model;
    }

    return false;
}

I then updated the sendByHandle function to do a few checks on the handle and try to find the email a different way. Here's the new sendByEmail function:

public function sendByHandle($handle, ChargeModel $chargeModel, $extra = [])
{

    if(is_int($handle)){
        $emailModel = $this->_getEmailModelById($handle);
    } else {
        $emailModel = $this->_getEmailModelByHandle($handle);
    }

    if($emailModel == false) {
        $emailModel = $this->_getEmailModelByName($handle);
    }

    if($emailModel == false) {
        craft()->charge_log->error('Failed to find email with the handle : '.$handle, ['extra' => $extra, 'charge' => $chargeModel]);
        return false;
    }

    $data['charge'] = $chargeModel;
    foreach($extra as $key => $arr) {
        $data[$key] = $arr;
    }

    $emailModel->send($data);
}

Looks like this is now working as it should. Hope it saves someone else some frustration.


texts: After upgrading to 2.5: Table 'alpineductless-craft.craft_elementindexsettings' doesn't exist

texts:
A client upgraded their site to 2.5, and I believe the update didn't finish.

At first there was a 500 error. I tried rolling the app back (code only) and it  gave an error that the database version didn't support rolling back. Replacing the craft/app directory with a fresh version of 2.5 fixed the 500 error.

The site and some of the admin area work, but in the control panel I cannot access Assets or Entries, I get this error:

CDbCommand failed to execute the SQL statement: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mysite.craft_elementindexsettings' doesn't exist

So it seems like something with the migration failed. Except must have not been fully failed, because of the error I got about the database version.

The catch is that the client didn't do a database backup before initiating the update, so there isn't a good rollback point.

Could I manually add this table? Any other potentially fixes for this? Is there a way to tell Craft to re-run the migration to 2.5?