1

I've set up a global set "attachmentGlobals" with a matrix field inside named "globalFiles". This matrix has only one block "files" which has a text field "fileId" and an Asset field "fileAsset".

I would like to retrieve a specific row searching for the "fileId" content.

I've triyed in those ways:

Test 1:

attachmentGlobals.globalFiles.fileId('sitelogo')

Return me an Error saying no method "fileId" is available

Test 2:

attachmentGlobals.globalFiles.find('fileId:sitelogo')

No error, but no results

Test 3:

attachmentGlobals.globalFiles.search('fileId:sitelogo')

No error, but no results

I've search Craft documentation and some examples on Stack Exchange, but nothing seems to help.

In the first place, is this possible? or were am I wrong?

Thank you in advance.

PS: I know this issue could be solved using only assets fields, but I would like to know if is possible to search for matrix fields by filed content.

1 Answer 1

1

As far as I know, (currently) the only way to filter matrix blocks is to use the type method to filter by block type or to limit the amount of returned matrix models with limit.

Here's what I'd do:

{% set searchString = 'sitelogo' %}

{# Search for potential matrix blocks #}
{% set foundBlocks = attachmentGlobals.globalFiles.type('files').search(searchString) %}

{# Loop through the result and output the right one #}
{% for foundBlock in foundBlocks %}

    {% if foundBlock.fileId == searchString %}
        <img src="{{ foundBlock.fileAsset.first.url }}" alt="{{ foundBlock.fileAsset.first.title }}">
    {% endif %}

{% endfor %}

You can't use search('fileId:sitelogo'), because that would filter for entries with fileId:sitelogo and not entries with a matrix block fileId:sitelogo.

2
  • How would you do that in a plugin? Nov 13, 2014 at 8:41
  • @David sorry, can't help you with a plugin solution. I've still no experience with php5 (yet)! Have a look at the methods available for MatrixBlockModel, you should be able to do the exact same conditional in your plugin. If you need further help, better ask a new question because I don't think many will notice your comment.
    – carlcs
    Nov 13, 2014 at 8:50

Your Answer

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

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