3

This is a great new feature of Craft 2.3:

It is now possible to set custom field parameters on Matrix block queries.

I was wondering what would happen, if two or more Matrix Block Types had a field with the same handle (e.g. myLightswitchField), and if it was possible to query for blocks across Block Types using this field as a parameter.

My example code doesn't return any blocks:

{% set blocks = entry.myMatrixField.myLightswitchField('1') %}

Yeah! There's {{ blocks|length }} Matrix blocks enabled.

This is just an example! I know that you can disable blocks from the block's context menu.

1 Answer 1

4

Unfortunately this is a limitation of that feature. In this case, both of your Lightswitch fields will be tweaking the DB query with their own WHERE [field_column_name] = 1, without knowledge of each other.

To avoid this, just give each of your Lightswitch fields their own unique handles.

If you want to get all the blocks where either one of your Lightswitch fields are checked, you could do this:

{% set blockIds = entry.matrixField.type('type1').typeOneLightswitchField(1).ids()
    |merge(entry.matrixField.type('type2').typeTwoLightswitchField(1).ids())
%}

{% for block in entry.matrixField.id(blockIds) %}
    ...
{% endfor %}

Not exactly a clean solution, but it’ll get the job done.

2
  • Thanks for the answer, Brandon. To clarify, I gave them the same handle by propose, to allow me to access them with the Matrix block query I posted in the example. I'll search for a workaround then! :)
    – carlcs
    Jan 29, 2015 at 20:07
  • @carlcs Ah, gotcha. Just updated my answer with a possible workaround. Jan 29, 2015 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.