I'm trying to upgrade my website to Craft 3 and can't resolve one issue with this piece of code:

{% for category in craft.categories.group('blogCategories').order('title') %}
   <li><a href="{{ category.url }}" class="button {{ entry.blogCategory.one().id == category.id ? 'light': 'primary' }}">{{ category.title }}</a></li>
{% endfor %}

I get the following error:

Twig Runtime Error – Twig\Error\RuntimeError Impossible to access an attribute ("id") on a null variable.

I can't find any information in Changes in Craft 3, but I bet there's a new way of getting the category ID of the current post and the entry.blogCategory.one().id won't work anymore?

Any ideas?


Ok, so it came out that the post I used for testing wasn't assigned to any category and that was causing the exception.

I added a validation for checking if the category is defined:

{{ (entry.blogCategory.one().id is defined and entry.blogCategory.one().id is not null) and entry.blogCategory.one().id == category.id ? 'light': 'primary' }}">{{ category.title }}</a></li>

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.