Search code examples
grailsgroovygsp

How to check an object exist or not in Gsp?


<g:each in="${clientTripInstance?.startPointJob?.passengerActivities}" status="i" var="startPassengerActivity">
     <g:if test = "${startPassengerActivity?.passengerCount > 1}">
         <p> ${startPassengerActivity?.activity}  ${startPassengerActivity?.passengerRole?.displayName} (${startPassengerActivity?.passengerCount})
     </p>
     </g:if>
     <g:else>
       <p> ${startPassengerActivity?.activity}  ${startPassengerActivity?.passengerRole?.displayName}
          </p>
     </g:else>
</g:each>

this code works fine when clientTripInstance?.startPointJob?.passengerActivities is exist.. there are some case when clientTripInstance?.startPointJob?.passengerActivities is not exist... so how to check is not exist ? i dont want to display anything if its not exist..

the domain class are

   class Trip {
            String notes
           List<PointJob> pointJobs = new ArrayList<PointJob>()
   }

   class PointJob {
       Point point
   List<PassengerActivity> passengerActivities = new ArrayList<PassengerActivity>();
   }


  class PassengerActivity {
    PassengerRole passengerRole;
    String activity;
    int passengerCount;

static constraints = {
    passengerRole()
    activity()
    passengerCount(nullable:true)
}

}


Solution

  • Can't you just wrap it all in another test to ensure the list isn't null or empty?

    <g:if test="${clientTripInstance?.startPointJob?.passengerActivities}">
      <g:each in="${clientTripInstance?.startPointJob?.passengerActivities}" status="i" var="startPassengerActivity">
        <g:if test = "${startPassengerActivity?.passengerCount > 1}">
          <p>
            ${startPassengerActivity?.activity}  ${startPassengerActivity?.passengerRole?.displayName} (${startPassengerActivity?.passengerCount})
          </p>
        </g:if>
        <g:else>
          <p>
            ${startPassengerActivity?.activity}  ${startPassengerActivity?.passengerRole?.displayName}
          </p>
        </g:else>
      </g:each>
    </g:if>