2

I'm filtering entries based off a searchbar with multiple parameters, and I'm building up an entries filter based off of them. Everything works great except for having more than one .search functions.

{% set req = craft.request %}

{% set results = craft.entries.section("properties") %}

{% set params = ['location', 'min-price', 'max-price', 'status'] %}
{% set query = {} %}

{% for param in params %}
  {% set key = param | camel %}
  {% set value = req.getParam(param) %}
  {% set query = query | merge({ (key):(value) }) %}
{% endfor %}

{% if query.location %}
  {% set results = results.search(query.location) %}
{% endif %}

{% if query.minPrice or query.maxPrice %}
  {% set min = query.minPrice ? query.minPrice : '' %}
  {% set max = query.maxPrice ? query.maxPrice : '' %}
  {% set results = results.search("price:" ~ '500000') %}
{% endif %}

{% if query.status %}
  {% set results = results.search('statusCategory:' ~ query.status) %}
{% endif %}

{% for entry in results %}
...

I've removed the whole min/max part just to simplify things, but it seems that if there is both a location and min/max price parameter, whichever one is last overrides the first. How can I combine these search parameters?

2

100% untested, but try something like this.

You're basically creating an array of all of your search criteria, then joining them into one .search() call at the end as a string separated with a space. That's because Craft does "and" searching with multiple terms by default.

{% set req = craft.request %}

{% set results = craft.entries.section("properties") %}

{% set params = ['location', 'min-price', 'max-price', 'status'] %}
{% set query = {} %}
{% set search = [] %}

{% for param in params %}
    {% set key = param | camel %}
    {% set value = req.getParam(param) %}
    {% set query = query | merge({ (key):(value) }) %}
{% endfor %}

{% if query.location %}
    {% set search = search|merge([query.location]) %}
{% endif %}

{% if query.minPrice or query.maxPrice %}
    {% set min = query.minPrice ? query.minPrice : '' %}
    {% set max = query.maxPrice ? query.maxPrice : '' %}
    {% set search = search|merge(["price:" ~ '500000']) %}
{% endif %}

{% if query.status %}
    {% set search = search|merge(['statusCategory:' ~ query.status]) %}
{% endif %}

{% if search|length %}
    {% set results = results.search(search|join(' ') %}
{% endif %}

{% for entry in results %}
    ...
1
  • Ah that makes sense. Appreciate it!
    – Joshua
    Sep 20 '17 at 22:23

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.