Search code examples
grailsgroovygsp

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 ?


Solution

  • 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.