1

Impossible to invoke a method ("getUrl") on a null variable

That's the error message generated by a blank search and some searches.

Fuzzy search is enabled in config/general.php, and it works. The search template is straight from the Craft CMS "search form" tutorial.

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search(query).order('score') %}

<h2>Search Results for "{{ query }}"</h2>
{% if entries|length %}
    {% for post in entries %}
        <div class="box col-sm-3">
            <div class="post-box vertical clearfix">
                <a href="{{ post.url }}" class="image-link arrow-icon dark-overlay"><img src="{{ post.postImage.first().getUrl('thumbImage')}}" width="434" height="434" alt=""></a>
                <div class="extra-info">
                    <h5><a href="{{ post.url }}">{{ post.title}}</a></h5>
                    <p class="meta small">{{ post.postDate | date('F d, Y') }} <a href="#">Nicole</a></p>
                </div>
            </div>
        </div>
    {% endfor %}
{% else %}
    <p>You search for "{{ query }}" didn't retun any results</p>
{% endif %}

{{ post.postImage.first().getUrl('thumbImage')}} works without error every place else.

Any ideas on what I am missing?

2

{{ post.postImage.first().getUrl('thumbImage')}}

Whatever entry post is referencing for whatever search term you're using when you get the error, doesn't have any postImage assets selected.

So when you call post.postImage.first(), that returns null and you can't call getUrl on null.

You can either make postImage required and make sure that all existing entries have at least one asset selected, or guard against it in Twig via:

{% set image = post.postImage.first() %}

{% if image|length %}
    {{ image.getUrl('thumbImage') }}
{% endif %}
2
  • So, postImage is a required field for every entry (post) in the posts section. The null is being thrown by a specific search fragment - taken directly from an entry that has a postImage. Searching an or an/ throws a null even though they are in the body of the post. Searching an/apn or an/apn-, which are still fragments, will output the post (image and all) in the search results. So, what is it about an and an/ that throws the null?
    – Hellyar
    Aug 30 '16 at 18:36
  • 1
    You should guard against it in twig (always). Even if you make it a required field, someone can delete the asset out from under you. In this case, you are searching not only entries in the post section, but other entries as well. One of them is matching, and it doesn't have a postImage. Aug 30 '16 at 20:18

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.