问题
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.
回答1:
You can make use of FacesContext#isValidationFailed(). It will return true
if validation has failed in the current JSF lifecycle. The current instance of FacesContext
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 itself rendered
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.
<f:ajax ... render="foo-holder" />
...
<h:panelGroup id="foo-holder">
<h:panelGroup id="foo" rendered="#{not facesContext.validationFailed}">
Validation has not failed.
</h:panelGroup>
</h:panelGroup>
Add if necessary layout="block"
to make them <div>
components instead of <span>
ones, depending on the final markup.
See also:
- Why do I need to nest a component with rendered="#{some}" in another component when I want to ajax-update it?
来源:https://stackoverflow.com/questions/30548586/conditionally-render-components-with-ajax-conditionally-only-if-validation-passe