0

So, in my template I get what I'm calling parentCategory, and I can output what I need:

{% set parentCategory = craft.categories.slug(craft.request.getSegment(2)) %}
{# parentCategory.title and parentCategory.slug output fine #}

But shortly after, I'm wanting to get all the descendants of parentCategory, like so:

{% set cats = craft.categories.descendantOf(parentCategory.id).find() %}
{# outputs all categories, whether descendants or not #}

It seems parentCategory.id is empty:

{{ parentCategory.id }}
{# outputs nothing #}

Any ideas where I'm going wrong here? Why is no ID being returned while title, slug and my custom fields are working fine?

Here's line 1 and 2 from my template:

{% if craft.request.getSegment(3) %}
    {% set parentCategory = craft.categories.slug(craft.request.getSegment(2)) %}

If I change line 2 to: {% set parentCategory = craft.categories.slug(craft.request.getSegment(2)).first() %}

I get the following error:

Craft\CategoryModel and its behaviors do not have a method or closure named "first".

Yet, I can repeat line 2 later in the template and include .first() and not get the error. What go on?

3

The craft.categories tag returns an ElementCriteriaModel, so parentCategory.title really shouldn't work. Try changing the first line of code to:

{% set parentCategory = craft.categories.slug(craft.request.getSegment(2)).first() %}
  • That's what I've been trying, but then I get the error: Craft\CategoryModel and its behaviors do not have a method or closure named "first". Have edited my question to show that. – Clive Portman Oct 29 '14 at 17:53
  • That is very weird indeed. Are you sure craft.request.getSegment(2) returns a valid slug? Have you tried hardcoding a known slug into the parameter instead? – André Elvan Oct 30 '14 at 9:01
  • Yep. Definitely does. – Clive Portman Oct 30 '14 at 16:09
  • @ClivePortman You’ve tried that exact line of code? That definitely should work. – Brandon Kelly Nov 1 '14 at 19:56
  • @BrandonKelly Definitely. I honestly can't add .first() to line 2 of my template, as described above, without the error. I can on the next line, but not if I remove line 2. – Clive Portman Nov 5 '14 at 15:33
0

If this is coming from a category’s primary URL – so a category variable is already defined for you – another way to get that category’s parent is by using the CategoryModel’s getParent() function:

{% set parentCategory = category.getParent() %}

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.