Saturday, January 24, 2015

JSF JSTL | Conditionally Display JSF Component: JSTL Tag vs. JSF Rendered Attribute

Initially I thought there were two approaches: using JSTL choose/when tags and using JSF rendered attribute.
However, I found that the first approach didn't work.
I wrote the following code and found that the 'otherwise' branch was always evaluated.
<c:choose>
    <c:when test="${status == 1}">
       <p:graphicImage value="green.png" />
    </c:when>
    <c:when test="${status == 2}">
       <p:graphicImage value="red.png" />
    </c:when>
    <c:otherwise>
       <p:graphicImage value="blue.png" />
    </c:otherwise>
</c:choose>
Buy Corel Painter 2015
Later I discovered explain to this issue at:
http://stackoverflow.com/questions/7437882/jstl-cchoose-cwhen-not-working-in-a-jsf-page, and
http://stackoverflow.com/questions/4870462/conditionally-displaying-jsf-components.
Simply speaking, JSTL tages are evaluated prior to JSF components processing.
So the second approach became the only choice.
<p:graphicImage value="green.png" rendered="#{status == 1}/>
<p:graphicImage value="red.png" rendered="#{status == 2}/>
<p:graphicImage value="blue.png" rendered="#{status != 1 and status != 2}/>
The above is the second approach.
However, this approach also has an issue.
I have a background appliation which sends status update at a certain interval. Upon receiving an update, the frontend application should update the web page.
So first I tried to add an ID to the graphicImage components in order to update one of them based on their id.
<p:graphicImage id="statusImage" value="green.png" rendered="#{status == 1}/>
<p:graphicImage id="statusImage" value="red.png" rendered="#{status == 2}/>
<p:graphicImage id="statusImage" value="blue.png" rendered="#{status != 1 and status != 2}/>
But JSF complained about duplicated IDs.

Finally I found a solution which was to use JQuery selector:
function updateStatusImage(status)
{
  var image;

  if (status == 1) image = 'green.png';
  else if (status == 2) image = 'red.png';
  else image = 'blue.png';

  $('#form img').attr('src', image);
}
Check more details here.


Create a Successful Online Store at Bigcommerce! Try it Free Now!

No comments:

Post a Comment