Illep
Illep

Reputation: 16859

Check, if a variable is null in a view

The following is a code segment from person.gsp

<g:set var="res" value="${ Person.get(personInstance.id) }" />
                            ${ res.result }

I get the following error message.

Cannot get property 'result' on null object

How can i do a validation to check if result is null from the view itself ?

Note: I don't want to do this validation from the controller

UPDATE

Can i do a

<g:if........${ Person.get(personInstance.id) } NOT EQUAL TO NULL THEN
<g:set var="res" value="${ Person.get(personInstance.id) }" />
                                ${ res.result }

Kind of a thing ? If so how to do it ?

Upvotes: 0

Views: 2293

Answers (2)

Szymon Stepniak
Szymon Stepniak

Reputation: 42272

Remember that you have a Safe Navigation operator in Groovy - ?.

If you type:

${res?.result}

it will avoid NPE and simply stop further evaluation if res is null. I is also a good practice to call Person.get(id) in the controller and set the result in the model you're associating with view. It will allow you to change your controller behaviour (e.g. reading from cache instead of database) without changing your view.

Upvotes: 2

Illep
Illep

Reputation: 16859

<g:if test="${Person.get(personInstance.id) != null}">
    <g:set var="res" value="${ Person.get(personInstance.id) }" />
    ${ res.result }
</g:if>

This worked.

Upvotes: -1

Related Questions