1

I have a category input. The category group has two levels.

enter image description here

When accessing the category input via Twig I am trying to only grab sub categories the user selected. However when I use

{% set firstCat = entry.categoryInput.first %}
{% set cats = firstCat.getDescendants() %}

or children it grabs all the descendants from Categories > Group not just from the structure that was selected from the input.

2

You could set the level parameter according to your requirements:

{% set cats = craft.categories({
    relatedTo: {
        sourceElement: entry,
        field: 'categoryInput'
    },
    level: 2,
    limit: null
}) %}
  • Will this work if the input is part of a matrix? – aran Oct 28 '15 at 19:02
  • 1
    You would then need to set field to myMatrixField.myCategoriesField. – carlcs Oct 28 '15 at 19:09
  • You pointed me in the correct direction. Using level(2) off of the input works. – aran Oct 28 '15 at 19:13
  • 1
    entry.myCategoriesField is actually just a shortcut for the full craft.categories criteria model I posted. So I'm surprised this solution doesn't work for you. – carlcs Oct 28 '15 at 19:22
  • This does work but I figured there should be a quicker way than calling craft.categories. When you wrote "set the level" I thought I would try using level(2) off of the input which worked. As you said it is returning a criteria model, which confused me as to why using getDescendants or children didn't work. – aran Oct 28 '15 at 19:38
0

@carlcs helped me stumble upon a solution. Using the .level(2) method gave the desired result.

{% set cats = entry.categoryInput.level(2) %}

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.