2

I'm confused about what to pass as a parameter in the descendantOf() function. I'm developing a website and passing an entry ID as a string (I also tested it as an integer) and everything went fine, untill now. Suddenly, when I try to use it with new template code, that doesn't work anymore. It does however still work in my template I wrote last week.

The docs say that the parameter has to be an EntryModel:

descendantOf #

Only fetch categories that are a descendant of a given category. Accepts a CategoryModel object.

In this thread on SE, someone says it can be an Entry ID.

descendantOf accepts either an EntryModel object or an entry’s ID.

However, if I use the next code (category is not a category group, I'm using a structure for it) where currentRegionId is an entryId as a string or integer:

{% for productCategory in product.productCategory.descendantOf(currentRegionId).order("title asc").find() %}

This works. But according to the docs, it shouldn't work, because I'm passing an ID and not an EntryModel.

It also works when I pass that ID while using eager loading:

{% set mainCategories = craft.entries({
    section:            'productCategories',
    level:              2,
    descendantOf:       currentRegionId,
    limit:              null,
    with:               ['productCategoryIcon']
}) %}

However, if I try the next piece of code in another template:

{% for category in entry.applyToCategories if category.descendantOf(currentRegionId) %}

I get this error:

Argument 1 passed to Craft\BaseElementModel::isDescendantOf() must be an instance of Craft\BaseElementModel, integer given

If I pass an EntryModel it does work as expected and according with the docs:

{% for category in entry.applyToCategories if category.descendantOf(craft.entries.id(currentRegionId).first()) %}

So what's going on? Is it something with the way I fetch my entries?

2

These are two different things.

{% set entries = myEntryModel.myEntriesField.descendantOf(var) %}

In this case the Entries field returns an ElementCriteriaModel object and you are setting the descendantOf parameter, which does in fact accept EntryModel objects or an Entry ID as an integer value. The Craft documentation is incomplete in this regard.

{% set bool = myEntryModel.isDescendantOf(var) %}

Here you are using the method isDescendantOf that is available for an EntryModel and returns whether the entry is a descendant of another entry. This method apparently only accepts an EntryModel.

| improve this answer | |
  • Looks like a solid explanation! Thanks. That'll be it I guess. – Tom De Smet Apr 25 '17 at 15:45

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.