I have a matrix inside of which I have 2 fields, 1. dropdown list containing download types and another asset field. I would like to search first by a category and then I would like to further filter them and see if they have downloads of a certain type.

I would like to avoid a 2 step searching if possible and search articles that belong to certain category that have a certain download type associated with it.

Any idea on how to achieve this?


You could loop through the Matrix field on every entry save using the awesome Preparse plugin, to store the categories an entry contains in a new field.


Here’s example code for your Preparse field, it would store strings like firstCategory,thirdCategory,secondCategory.

{%- set categories = [] %}

{%- for block in entry.myMatrixField.type('myRelevantBlockType') %}
    {%- if block.myDropdownField %}
        {%- set categories = categories|merge([ block.myDropdownField.value ]) %}
    {%- endif %}
{%- endfor %}

{{- categories|join(',') -}}

Once you have populated that field for all your entries, you can filter them by a category using this criteria model.

{% set categoryToSearch = 'secondCategory' %}

{% set entries = craft.entries({
    section: 'myEntriesSection',
    search: 'myPreparseFieldHandle:*' ~ categoryToSearch ~ '*',
}) %}

I have to say that I’m not very proud of this solution as it uses search which I usually try to avoid. But I wasn’t able to come up with a better idea.

|improve this answer|||||
  • How would this work with existing imported content? I have imported over 65K + entries and about 7K entries need that. – Subrato M Nov 16 '16 at 15:02
  • Disable devMode, then go to Settings > Section > My Section where you click "Save" (you don’t have to edit any section settings). This should trigger a "Re-save Elements" task which should update all Preparse fields as well. 65K entries will take a while! – carlcs Nov 16 '16 at 16:23
  • Thanks @carlcs I am going to give it a try and hopefully, it takes care of this easily – Subrato M Nov 17 '16 at 20:16
  • I haven't really worked on onSave events, can you expand on it? Also sorry been busy with other stuff so craft was on backburner. I am looking at ParseFieldPlugin.php. Do I assign categories | join(',') to new text field? – Subrato M Dec 1 '16 at 16:38
  • So I am not sure what I did wrong. I installed the plugin, created a field of that type, added it to my section, added the code you as an example and saved it. The field doesn't have any value. Is there a way to debug and see if what I did was right or wrong? Also ignore my previous comment – Subrato M Dec 1 '16 at 17: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.