Discussions

Ask a Question
Back to All

How to filter by a select field, with a regex?

I've a problem with what a think to be a very common task.
I want to filter content entries by the value selected by the user; and if the user doesn't select any value, I want to show all content entries.

So, let's say I have a Product model, with a "name" and "category" fields. Name is a string field, and category is a select field. Given the above, the following code DO what I expected:

{% assign requested_product_name = '/' | concat: params['requested_product_name'], '/' %}

{% with_scope name: requested_product_name %}
    {% for product in contents.products %}
        /* PREVIEW PRODUCT */
    {% endfor %}    	
{% endwith_scope %}

i.e. it show all products if requested_product_name parameter contain the .* regex.

But if I use the category field, the regex dosn't work anymore!

For example, if category field has two select_options, let's say "books" and "sunglasses", then the following code:

{% assign requested_product_category = '/' | concat: params['requested_product_category'], '/' %}

{% with_scope category: requested_product_category %}
    {% for product in contents.products %}
        /* PREVIEW PRODUCT */
    {% endfor %}    	
{% endwith_scope %}

show only the entries belonging to the "books" category (the first select option specified).

The question is: how to show all entries when the user doesn't pick a filter value in the UI? I can use some "if/then" logic, but with multiple filters, the code can become very lengthy and confusing.