Conditional rendering in JSF [duplicate]

拜拜、爱过 提交于 2019-11-29 06:33:22

The JSF component's rendered attribute is a server-side setting which controls whether JSF should generate the desired HTML or not.

The <f:ajax> tag's render attribute should point to a (relative) client ID of the JSF-generated HTML element which JavaScript can grab by document.getElementById() from HTML DOM tree in order to replace its contents on complete of the ajax request.

However, since you're specifying the client ID of a HTML element which is never rendered by JSF (due to rendered being false), JavaScript can't find it in the HTML DOM tree.

You need to wrap it in a container component which is always rendered and thus always available in the HTML DOM tree.

<h:commandButton action="#{Bean.method()}"  value="Submit">
   <f:ajax execute="something" render="messages" />
</h:commandButton>

<p>
    <h:panelGroup id="messages">
        <h:outputFormat rendered="#{Bean.answer=='one'}" value="#{messages.one}"/>
        <h:outputFormat rendered="#{Bean.answer=='two'}" value="#{messages.two}"/>
    </h:panelGroup>
</p>

Unrelated to the concrete problem, you've there a possible design mistake. Why would you not just create a #{Bean.message} property which you set with the desired message in the action method instead, so that you can just use:

<h:commandButton action="#{Bean.method()}"  value="Submit">
   <f:ajax execute="something" render="message" />
</h:commandButton>

<p>
    <h:outputFormat id="message" value="#{Bean.message}" />
</p>
Jonathas Pacífico

I know it's not the central point of the question, but as I had this problem many times in the past, I just post it here to help others who are in need. For those who uses PrimeFaces there's a component in PrimeFaces Extension called Switch.

Sometimes you need to display different outputs or components depending on a value. Usually you can achieve this by using the ui:fragment tag. With the pe:switch util tag you won't have to declare ui:fragment tags, with different checks like ui:fragment rendered="#{!empty someController.value}", anymore.

Eng Ahmed Hamed
style="visibility: #{questionchoose.show==false ? 'hidden' : 'visible'}"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!