Conditionally render components with ajax conditio

2019-07-19 08:30发布

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条回答
Summer. ? 凉城
2楼-- · 2019-07-19 09:13

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:

查看更多
登录 后发表回答