1

I am not super fluent in Twig and I inherited a website from a company that built the site in Craft v2. The site was upgraded to version 3 of Craft recently and one of the template pages is throwing an error where on version 2 of Craft it was not. Code:

{% set faqs = craft.entries.section('FAQ').search('slug::' ~ entry.slug).first() %}

{% if faqs.questionsanswers|length > 0 %}
  <a href="#link">FAQs</a>
{% endif %}

This is throwing an error: Impossible to access an attribute ("questionsanswers") on a null variable.

So since it was returning null I changed the code to this which seems to be working:

{% if faqs is not null and faqs is not empty %}
  <a href="#link">FAQs</a>
{% endif %}

My question is why would this code not work for version 3 when it was working correctly for version 2? Why would the length return null instead of 0? I did not do the upgrade but maybe something was missed? (This is a template page and some of the entries do have FAQs and some don't) Or perhaps something with the structure of the version 3 of Craft has changed? Lastly if there is a better way to do/code what is being done I would love to hear it.

2

The error tells you that faqs is null. As you're using the first() function to execute your element query, this means that your query has no matches.

  1. Are you sure that the section handle (FAQ) is in uppercase?
  2. The correct way to create an entry query in Craft 3 is craft.entries(). Although it may work without the parenthesis, it can't hurt to add them.
  3. You can replace .search('slug::' ~ entry.slug) with .slug(entry.slug). It's easier to understand and should have the same effect.
  4. Are you sure that the query always returned something in Craft 2? It may be worth adding a null check to avoid the error: {% if faqs and faqs.questionsanswers and faqs.questionsanswers|length > 0 %}
| improve this answer | |
  • Thanks a lot for your reply, your insight is very helpful and I have already used some of your suggestions to help better format the code. – crazymatt Sep 15 at 18:10

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.