1

Is there a way in Craft to filter assets by an associated category?

In asset settings, one of our asset sources has been given a category field, and those assets have been given a category.

ie; asset source "documentLibrary" has category field "documentType" and asset "documentOne" has documentType "sitePlan".

I have tried the following variations below:

craft.assets({documentType: "sitePlan"})
craft.assets({documentType: "contains, sitePlan"})
craft.assets({documentType: "LIKE '%sitePlan%'"})
craft.assets({documentType: array('sitePlan')})
craft.assets({count(documentType): '> 0'})
craft.assets({relatesTo: "sitePlan"})
2

You first have to get the CategoryModel of that category you want to filter by. Use slug as a parameter and the first() method to get the first and only category matching that criteria.

This CategoryModel is the target element of your relation. Set your craft.assets ElementCriteriaModel using the relatedTo parameter to filter by your category and also set the relation's field name here (not necessary if you don't have other relations set on your assets).

If you really have the need to further filter by an asset source (don't get the assets which match the other criteria but are in a different source folder), you (currently) can only do this by looking up that asset source's ID in the database and filter by that sourceId. Set all other parameters to your needs.

{% set categorySlug = 'sitePlan' %}

{# Get the CategoryModel #}
{% set category = craft.categories.slug(categorySlug).first() %}

{# Get the assets related to this CategoryModel #}
{% set assets = craft.assets({
    relatedTo: {
        targetElement: category,
        field: 'documentType',
    },
    sourceId: '1',
    limit: null,
    order: 'dateUpdated desc',
}) %}
| improve this answer | |
  • Much better answer. I really shouldn't be answering craft questions after drinking all night. Mine was just plain wrong. Thanks for coming to the rescue. ;) – Douglas McDonald Nov 6 '14 at 10:08
  • That's the reason!! I thought someone hijacked your account, @Douglas. :D – carlcs Nov 6 '14 at 10:12
  • haha. thanks guys. got me out of a bind ;) – Jered Masters Nov 7 '14 at 1:03

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.