Elbek
Elbek

Reputation: 3484

Conditionally rendering <h:commandButton> using <c:if>

I am using jstl for small testing. And it is not working how it is supposed to work

here is the small code:

<c:set var="id" value="#{mBlog.blog.id}"/>
                    ${id}    //printing  4  
                    <c:if test="${id > 0}">
                        <h:commandButton value="Update" action="#{mBlog.update}"/>  //is not rendered
                    </c:if>

                    <c:if test="${id == 0}">
                        <h:commandButton value="Save" action="#{mBlog.save}"/>  //is not rendered
                    </c:if>

I do not know what is wrong. in the display i see only 4, nothing else.

Upvotes: 2

Views: 4887

Answers (1)

BalusC
BalusC

Reputation: 1108732

JSTL tags and JSF UI components doesn't run in sync as you'd expect from the coding. Long story short: JSTL in JSF2 Facelets... makes sense? Read this carefully.

In your particular case, the JSTL <c:if> tag condition seems to be dependent on the result of the JSF <f:event> tag. At the moment the <c:if> runs, during the view build time, the <f:event> hasn't run yet, because it runs during pre render view event. Hence the #{mBlog.blog.id} is always null or any other default.

You need to use JSF component's rendered attribute instead. It also keeps your code cleaner.

<h:commandButton value="Update" action="#{mBlog.update}" rendered="#{mBlog.blog.id gt 0}" />
<h:commandButton value="Save" action="#{mBlog.save}" rendered="#{mBlog.blog.id eq 0}" />

You've however another potential future problem when invoking the action. Make sure that the bean is put in view scope, not in the request scope.

Upvotes: 6

Related Questions