本文介绍了仅当验证通过时,才有条件地使用ajax有条件地渲染组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSF 2.2,我想知道是否有一种方法只有在验证通过后才有条件地使用ajax渲染组件.通过使用ajax的render属性,无论是否通过验证,都将呈现组件.我追求的是这样的:

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>

是否可以通过类似的方式有条件地渲染组件?在我的情况下,我不想在片段中包含rendered属性并将其设置为true或false,因为如果验证失败,这会使片段在DOM中根本不存在.我可能在例如与面板进行一些交互之后通过jQuery获取的panelGroup内部的组件中具有特定的css样式,并且如果验证失败,我不想呈现该部分,因此它可以保持其当前的可视状态.

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.

推荐答案

您可以使用 FacesContext#isValidationFailed() .如果在当前JSF生命周期中验证失败,它将返回true. FacesContext的当前实例在EL中也可以作为#{facesContext}使用.

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}.

只需在rendered属性中对其进行检查并更新其父占位符组件.请注意,您不能有条件地渲染本身具有rendered属性设置为JavaScript的组件,否则将无法找到和更新它.您的理论<f:ajax>尝试将以同样的方式失败.

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.

例如

<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>

根据最终标记,如有必要,添加layout="block"使其成为<div>组件,而不是<span>组件.

Add if necessary layout="block" to make them <div> components instead of <span> ones, depending on the final markup.

这篇关于仅当验证通过时,才有条件地使用ajax有条件地渲染组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-15 23:32