3

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

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

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

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

5

You can build the array for your criteria model's relatedTo parameter step for step before adding it:

{# Initial criteria model #}
{% set exhibitions = craft.entries.section('exhibitions').limit(null) %}

{# Compose relatedTo parameter #}
{% set relatedToParam = ['and'] %}

{% if query.art is defined %}
    {% set catIds = craft.categories.group('artCategories').id(query.art).ids() %}
    {% set relatedToParam = relatedToParam|merge([{ targetElement: catIds }]) %}
{% endif %}

{% if query.location is defined %}
    {% set catIds = craft.categories.group('locationCategories').id(query.location).ids() %}
    {% set relatedToParam = relatedToParam|merge([{ targetElement: catIds }]) %}
{% endif %}

{# Add additional criteria. Avoid passing an array with 'and' only #}
{% if relatedToParam|length > 1 %}
    {% set exhibitions = exhibitions.relatedTo(relatedToParam) %}
{% endif %}
2
  • 1
    Just adding a link back to this post, as it explains how you're setting craft.request.getQuery() and accessing it's parameter query.art (I haven't seen this method before). Does getQueryString() do the same thing?
    – Rob
    Jan 19 '16 at 20:27
  • 1
    Yes, this is right, getQueryString() returns the complete query string and getQuery() (without a param) returns the query string converted to an array.
    – carlcs
    Jan 19 '16 at 21:13

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.