LocomotiveCMS

The Locomotive V3 Developer Hub

Welcome to the Locomotive V3 developer hub. You'll find comprehensive guides and documentation to help you start working with Locomotive V3 as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    
Ask A Question

Questions

0

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.

Posted by Riccardo 2 years ago