1

I have the following code where I'm pulling entries related to another entry which works fine. However I also want to limit the entries returned on a category page and thus am merging in a relatedTo: category

However on the category page it is returning all entries related to that category, not limited to the category AND the related entry

{% set myStation = getCookie('myStation') %}
{% set relatedStation = craft.entries.id(myStation) %}


{# set pagination/categories #}
{% set params = { section: 'blog', limit: 6, offset: 1, relatedTo: relatedStation } %}
{% if category is defined %}
  {% set params = params | merge({ relatedTo: category }) %}
{% endif %}

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

I see the docs includes 'and' (bottom of the page) but I'm not sure how to get that in there using merge. Please advise.

3

Something like this should work:

{% set myStation = getCookie('myStation') %}
{% set relatedStation = craft.entries.id(myStation) %}

{% set params = { section: 'blog', limit: 6, offset: 1, relatedTo: relatedStation } %}

{% if category is defined %}
    {% set params = params|merge({relatedTo: ['and',
        { element: relatedStation },
        { element: category }
    ]}) %}
{% endif %}

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

The trick with merge is that it will always replace matching keys that it finds. So you need to tell it to replace it with the proper and syntax.

| improve this answer | |
  • no offense - but did you "solve" the "object could not be converted to an array" error in this case? A few weeks ago I tried your syntax with Craft 3 ['and', category, query, elementId] and received an exception. I've solved it by doing ['and', ['element': category], [...]] there was a question here about the same thing because someone else had the same issue – Robin Schambach May 18 '18 at 22:10
  • Seems like it's not the case... As you can see here github.com/craftcms/cms/blob/master/src/elements/db/… the first index will be removed (the "and") and the 2nd index, your relatedStation object will be passed to the subParse function.. At this point you are trying to merge an array with an object github.com/craftcms/cms/blob/master/src/elements/db/… Sry if this is the wrong place for this.. I'll delete it if that's the case – Robin Schambach May 18 '18 at 22:22
  • No offence at all. :) But I think you're right looking at the code. Will update the answer and maybe even test it this time. – Brad Bell May 18 '18 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.