I would like to do a check in a GSP page. I have a list of products. the list contains about 21 products. I use g:each to loop the products in GSP and if/else for the check. see my code below. but if the product.id not eaqual to 3. The page displays/prints the checkBox "dontCallMe" 21 times and I expect to print it one time. why is that? is there other way to do the check? thanks
<g:each in="${products}" var = "product">
<g:if test="${product.id == '3'}">
<tr>
<td>
<g:checkBox name="callMe" checked="true"
value=""/> Call me
</td>
</tr>
</g:if>
<g:else>
<tr>
<td>
<g:checkBox name="callMe" checked="false"
value=""/> Call me
</td>
</tr>
</g:else>
<g:if test="${product.id == '4'}">
<tr>
<td>
<g:checkBox name="callMeAgain" checked="true"
value=""/> Call me again
</td>
</tr>
</g:if>
<g:else>
<tr>
<td>
<g:checkBox name="callMeAgain" checked="false"
value=""/> Call me again
</td>
</tr>
</g:else>
<g:if test="${product.id == '5'}">
<tr>
<td>
<g:checkBox name="dontCallMeAgain" checked="true"
value=""/> Dont call me again
</td>
</tr>
</g:if>
<g:else>
<tr>
<td>
<g:checkBox name="dontCallMeAgain" checked="false"
value=""/> Dont call me again
</td>
</tr>
</g:else>
</g:each>
If you have 21 products and the dontCallMe
appears 21 times it means your condition is always false.
What I would do is open up the code in the debugger
and verify that the object has the expected value and type that you expect.
If your not using a debugger, add a new <td>
<td>
`${product.id}`
</td>
Also, if you don't have a debugger try something like this (havn't tried it myself):
<td>
`${product.id?.getClass()}`
</td>
Finally, the code could be simplified as follows (please excuse typos):
<g:each in="${products}" var = "product">
<tr>
<td>
<g:checkBox name="${product.id == '3' ? 'CallMe' : 'DontCallMe'}"
checked="${product.id == '3' ? 'true' : 'false'}"
value=""/>${product.id == '3' ? 'CallMe' : 'DontCallMe'}"
</td>
<td>
DEBUG: ${product.id} <br/>
DEBUG: ${product.id?.getClass()} <br/>
</td>
</tr>
</g:each>