1

Bit of an unusual one and sure must be missing something but know if we have a defined lightswitch field we want to filter against it can quite easily be done so like this:

{{ craft.products().myField(1) }}

However, if I have several lightswitch fields and a front-end filtering form I don't especially want to explicitly do this against all of them, eg {{ craft.products().myField(1).anotherField(9) }}. Was wondering then if it is possible to build out some kind of dynamic search or filter but unless doing something crazy looks like the Craft search parameter won't filter against lightswitch fields, eg the following won't work:

{{ craft.products().search('myField:1') }}

I think I have found a workaround using the where() parameter but feels a bit … inelegant … as essentially specifying my query now against DB values rather than against Craft elements/properties:

{{ craft.products().where('field_myField=1') }}

Any thoughts on improving? Is there a way to do this in native Craft/twig without having to query against specific database values?

Cheers,

Cole

PS above are examples working with Craft Commerce Products. Not entirely sure if this is an issue limited to products as opposed to - say - entries but as these are both essentially elements had assumed not.

  • 1
    Searching against lightswitch should work. Did you tick Use this field’s values as search keywords on your fields? – Oli Oct 13 at 14:37
  • Bingo - I had updated the fields to be searchable but hadn't refreshed the search index. php craft resave/products --update-search-index has resolved. Thanks! – Cole Henley Oct 14 at 15:22
  • Excellent! Glad you're sorted :) – Oli Oct 14 at 15:33
  • Someone want to add an official answer for this? :) – Brad Bell Oct 15 at 4:27
2

Searching against lightswitch should work. Make sure Use this field’s values as search keywords is checked in Settings → Fields → your field then run ./craft resave/entries --update-search-index to (re)index your values.

| improve 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.