I am using JSF 2.2 and I was wondering if there is a way to render components with ajax conditionally only if the validation passes. By using the render attribute of ajax the components will be rendered regardless of the validation passing or not. What I'm after is something like:
<f:ajax ... render="#{validationHasPassed ? 'foo' : ''}" />
...
<h:panelGroup id="foo">
<!-- other components here -->
</h:panelGroup>
Is it possible to conditionally render a component in a similar way like this? In my case I don't want to have the rendered attribute in a fragment and set it to true or false, as this makes the fragment not exist at all in the DOM if validation fails. I might have specific css styling for example in the components inside the panelGroup that has been acquired through jQuery after some interaction with the page and I don't want to render the section if validation fails, so that it can remain in its current visual state.
You can make use of
FacesContext#isValidationFailed()
. It will returntrue
if validation has failed in the current JSF lifecycle. The current instance ofFacesContext
is available also in EL as#{facesContext}
.Just check it in the
rendered
attribute and update its parent placeholder component. Do note that you can't conditionally render a component which has by itselfrendered
attribute set as JavaScript would otherwise not be able to find and update it. Your theoretical<f:ajax>
attempt would have failed the same way.E.g.
Add if necessary
layout="block"
to make them<div>
components instead of<span>
ones, depending on the final markup.See also: