1

I'm creating a filter and would like to return entries that must contain multiple categories (and behavior, not or). A sample url would be /events?cat=2,3.

{% set eventCat = craft.request.getParam('cat') %}
{% set events = craft.entries.relatedTo(eventCat).all() %}

Gives me "or" behavior and

{% set eventCat = craft.request.getParam('cat') %}
{% set events = craft.entries.relatedTo('and', eventCat).all() %}

Doesn't give me any results.

(updated to reflect Craft 3 syntax, thanks Robin!)

3

This should do it:

{% set eventCats = craft.request.getParam('cat')|split(',') %}
{% set events = craft.entries.relatedTo(['and']|merge(eventCats)).find() %}
  • I'm getting an "Argument #2 is not an array" error - eventCats is definitely an array, is this a syntax error? – Matthew Rotter Sep 25 '18 at 0:34
3

Answer for Craft 2

Your final result should not look like relatedTo('and', '1,2') but

relatedTo('and, 1, 2')

Or

relatedTo(['and', 1, 2])

So you just need to do

relatedTo('and,' ~ param)

Keep in mind to code defensively, so you might want to check if your query param is not null or something

Answer for Craft 3

relatedTo(['and', ['element' => 1], ['element' => 2]])
  • "Argument #2 is not an array" for any of these syntaxes. Is it because of how craft 3 has changed the relations syntax? Or am I being a goober somehow? – Matthew Rotter Sep 25 '18 at 1:30
0
{% set eventCats = craft.request.getParam('cat') %}
{% set eventCats = eventCats|split(',') %}

{% set cats = [] %}

{% for eventCat in eventCats %}
    {% set cats = cats|merge([{element: eventCat}]) %}
{% endfor %}

{% if cats|length > 0 %}
    {% set cats = ['and']|merge(cats) %}
{% endif %}

{% set events = craft.entries.relatedTo(cats) %}

Shout out to Stephen Hamilton who came up with this answer.

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.