<p>You're close...</p>

<pre><code>{% set programImage = entry.programImage.one() %}
{% if programImage %}
    &lt;img src="{{ programImage.getUrl() }}" alt=""/&gt;
{% endif %}
</code></pre>

<p>You get the the asset model (or null), then check if you actually have it, then finally use it.</p>

<p>It's essentially the same in Craft 2.</p>

CC BY-SA 3.0
2018-04-14T13:57:32.050Z
I want this to work.  But, still not joy.   It still reads `impossible to invoke a method on a null variable.`. What I don't understand is that the `imageCaption` field is blank and this templating approach given in the Mijingo Craft3 course works for the `imageCaption` but does not translate to my attempt to apply it to `programImage`.  ``  {% if entry.programImageCaption %}
            <p class="caption">
                <small>{{ entry.programImageCaption }}</small>
            </p>
            {% endif %}``
Hellyar
CC BY-SA 3.0
2018-04-14T14:10:50.533Z
I missed on thing.  I kept `entry.programImage` in the `if` statement.  I removed it, and it works. Thanks all.
Hellyar
CC BY-SA 3.0
2018-04-13T21:59:28.620Z
2018-04-13T21:59:28.620Z
Lindsey D
<p>I talk about this type of "defensive coding" extensively in the <a href="https://nystudio107.com/blog/handling-errors-gracefully-in-craft-cms" rel="nofollow noreferrer">Handling Errors Gracefully in Craft CMS</a> article, if it helps.</p>

<p>The TL;DR is that the null coalescing operator is your friend:</p>

<p><code>
{% set image = entry.someImage.first() ?? someGlobal.defaultImage.first() ?? null %}
{% if image and image.kind == "image" %}
    &lt;img src="{{ image.getUrl() }}" /&gt;
{% endif %}
</code></p>

CC BY-SA 3.0
2018-04-14T17:33:49.893Z
2018-04-14T17:33:49.893Z
andrew.welch
<p>I ran into the same problem a couple of days ago (Craft newbie). I wanted to make it obvious that the image was missing, so I uploaded an image asset for the "No image" case. Then in the template, I used this for the src attribute on the image tag:</p>

<pre><code>{{(entry.programImage.one() ?? craft.assets.id(47).one()).getUrl()}}
</code></pre>

<p>It's using the null coalescing operator <strong>??</strong>, so if entry.programImage.one() is <em>not</em> <strong>null</strong>, it gets returned and if it <em>is</em> <strong>null</strong> it loads a specific image asset (my 'no image' picture, represented by id 47). Then it does a getUrl on which ever image is selected.</p>

CC BY-SA 3.0
2018-04-14T13:11:30.423Z
2018-04-14T13:11:30.423Z
Nik Shenoy
<p><code>entry.programImage</code> does not contain the image. It is a prepared query to fetch the database row and populate the model. In order to gain the model/the asset you have to do <code>entry.programImage.one()</code> which will return the element or null. </p>

<pre><code>{% if entry.programImage.one() %}
   ...
{% endif %}
</code></pre>

<p>If you want to make sure to check if the field is even in the layout you have to do</p>

<pre><code>{% if entry.programImage is defined and entry.programImage is not empty %}
    {% set asset = entry.programImage.one %}
    {% if asset is not null %}
       You have an image
    {% endif %}
{% endif %} 
</code></pre>

CC BY-SA 3.0
2018-04-14T13:54:02.863Z
So, my initial construct was based on replicating the approach that works for the image caption.  This is the approach given in the Mijingo Craft 3 training course.       ``{% if entry.programImageCaption %}
            <p class="caption">
                <small>{{ entry.programImageCaption }}</small>
            </p>
            {% endif %}.``
Hellyar
CC BY-SA 3.0
2018-04-14T13:55:18.803Z
@Hellyar Yes but this was an example for a string, currently you don't have a string but an object. You need to know what type of variables you use
Robin Schambach
CC BY-SA 3.0
2018-04-14T14:14:20.043Z
I have both solutions up an running now. I did not think of the `string` vs. `object` angle.  I wrongly assumed if it worked for one field it would work for the other.  I have both solutions up and running now.  Thanks.
Hellyar
CC BY-SA 3.0
2018-04-14T14:18:43.630Z
Every field returns a different variable. Many people tend to assume they only receive strings or an array of elements in Craft fields but most of them return something else. They just have a `__toString()` function in order to display the mostly assumed data when you do `entry.fieldHandle` that's the way how Redactor fields work
Robin Schambach
CC BY-SA 3.0
2018-04-13T22:02:39.100Z
2018-04-13T22:02:39.100Z
Robin Schambach
<p>Here is my templating...</p>

<pre><code>      {% if entry.programImage %}
        &lt;img src="{{ entry.programImage.one().getUrl() }}" alt=""/&gt;
      {% endif %}
</code></pre>

<p>The field <code>programImage</code> is NOT required.  </p>

<p>The image does display for entries that have it.<br>
It throws an ERROR for those that do not.  </p>

<p>The ERROR message is as follows.</p>

<pre><code>Impossible to invoke a method ("getUrl") on a null variable.
</code></pre>

<p>What am I missing?</p>

<p>Thanks</p>

<templating>
How do you template an IF statement to avoid an error if an image is not assigned
# How do you template an IF statement to avoid an error if an image is not assigned

(Asked by: username_0 on 2018-04-13)

Here is my templating...
      {% if entry.programImage %}
        
      {% endif %}

The field programImage is NOT required.  
The image does display for entries that have it.
It throws an ERROR for those that do not.  
The ERROR message is as follows.
Impossible to invoke a method ("getUrl") on a null variable.

What am I missing?
Thanks

**Tags:** templating

---

## 4 answers

### Answer by username_1 on 2018-04-13. Score: 3 | Accepted answer

You're close...
{% set programImage = entry.programImage.one() %}
{% if programImage %}
    
{% endif %}

You get the the asset model (or null), then check if you actually have it, then finally use it.
It's essentially the same in Craft 2.

> **Comments:**
> **username_0**: I want this to work.  But, still not joy.   It still reads `impossible to invoke a method on a null variable.`. What I don't understand is that the `imageCaption` field is blank and this templating approach given in the Mijingo Craft3 course works for the `imageCaption` but does not translate to my attempt to apply it to `programImage`.  ``  {% if entry.programImageCaption %}             <p class="caption">                 <small>{{ entry.programImageCaption }}</small>             </p>             {% endif %}``  
> **username_0**: I missed on thing.  I kept `entry.programImage` in the `if` statement.  I removed it, and it works. Thanks all.  

---

### Answer by username_2 on 2018-04-14. Score: 2

I talk about this type of "defensive coding" extensively in the [Handling Errors Gracefully in Craft CMS](https://nystudio107.com/blog/handling-errors-gracefully-in-craft-cms) article, if it helps.

The TL;DR is that the null coalescing operator is your friend:

`{% set image = entry.someImage.first() ?? someGlobal.defaultImage.first() ?? null %}
{% if image and image.kind == "image" %}
![]({{ image.getUrl() }})
{% endif %}`


---

### Answer by username_3 on 2018-04-14. Score: 1

I ran into the same problem a couple of days ago (Craft newbie). I wanted to make it obvious that the image was missing, so I uploaded an image asset for the "No image" case. Then in the template, I used this for the src attribute on the image tag:
{{(entry.programImage.one() ?? craft.assets.id(47).one()).getUrl()}}

It's using the null coalescing operator ??, so if entry.programImage.one() is not null, it gets returned and if it is null it loads a specific image asset (my 'no image' picture, represented by id 47). Then it does a getUrl on which ever image is selected.


---

### Answer by username_4 on 2018-04-13. Score: 1

entry.programImage does not contain the image. It is a prepared query to fetch the database row and populate the model. In order to gain the model/the asset you have to do entry.programImage.one() which will return the element or null. 
{% if entry.programImage.one() %}
   ...
{% endif %}

If you want to make sure to check if the field is even in the layout you have to do
{% if entry.programImage is defined and entry.programImage is not empty %}
    {% set asset = entry.programImage.one %}
    {% if asset is not null %}
       You have an image
    {% endif %}
{% endif %}

> **Comments:**
> **username_0**: So, my initial construct was based on replicating the approach that works for the image caption.  This is the approach given in the Mijingo Craft 3 training course.       ``{% if entry.programImageCaption %}             <p class="caption">                 <small>{{ entry.programImageCaption }}</small>             </p>             {% endif %}.``  
> **username_4**: @Hellyar Yes but this was an example for a string, currently you don't have a string but an object. You need to know what type of variables you use  
> **username_0**: I have both solutions up an running now. I did not think of the `string` vs. `object` angle.  I wrongly assumed if it worked for one field it would work for the other.  I have both solutions up and running now.  Thanks.  
> **username_4**: Every field returns a different variable. Many people tend to assume they only receive strings or an array of elements in Craft fields but most of them return something else. They just have a `__toString()` function in order to display the mostly assumed data when you do `entry.fieldHandle` that's the way how Redactor fields work  

---

