如何在bean的动作方法中的UIData组件内收集UIInput组件的值? [英] How to collect values of an UIInput component inside an UIData component in bean's action method?

查看:134
本文介绍了如何在bean的动作方法中的UIData组件内收集UIInput组件的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在bean的动作方法中以 UIData 组件的顺序收集 UIInput 组件的值验证重复值。我试图将 UIInput 组件绑定到一个bean属性并获取其值,但它打印 null 。如果我把它放在datatable之外,那么它会打印预期的值。 datatable有什么问题吗?

I'm trying to collect values of an UIInput component inside an UIData component during bean's action method in order to validate duplicate values. I tried to bind the UIInput component to a bean property and getting its value, but it prints null. If I place it outside the datatable, then it prints the expected value. Is there something wrong with the datatable?

<rich:dataTable binding="#{bean.table}" value="#{bean.data}" var="item">
    <h:column>
        <f:facet name="header">
            <h:outputText value="Field1" />
        </f:facet>
        <h:inputText binding="#{bean.input}" value="#{item.field1}" />
    </h:column>
</rich:dataTable>

以下是支持bean代码:

Here's the backing bean code:

private UIData table;
private UIInput input;

public void save() {
    System.out.println(input.getId() + " - " + input.getValue());
}


推荐答案

datatable没有错。 JSF组件树中的只有一个 UIInput 组件,每当父级 UIData 组件迭代模型的每个项目。因此,在 UIData 迭代期间,而不是之前或之后,状态才可用。您正在尝试访问bean的操作方法中的单个组件的值,而父 UIData 组件不会遍历它,因此值将始终返回 null

There's nothing wrong with the datatable. There's only one UIInput component in the JSF component tree whose state get changed everytime whenever the parent UIData component iterates over every item of the model. The state is thus only available during the UIData iteration and not before or after. You're trying to access the value of a single component in the bean's action method while the parent UIData component isn't iterating over it, so the values will always return null.

您需要通过 UIComponent#visitTree() UIData 上收集感兴趣的信息 VisitCallback 实现。

You need to visit the component tree by UIComponent#visitTree() on the UIData and collect the information of interest in the VisitCallback implementation.

table.visitTree(VisitContext.createVisitContext(FacesContext.getCurrentInstance()), new VisitCallback() {
    @Override
    public VisitResult visit(VisitContext context, UIComponent target) {
        if (target instanceof UIInput) {
            UIInput input = (UIInput) target;
            System.out.println("id: " + input.getId());
            System.out.println("value: " + input.getValue());
        }

        return VisitResult.ACCEPT;
    }
});

顺便说一下,您通常会使用正常的验证器执行验证 UIInput 组件中,或者在这种特殊情况下可能更好,一个 ValueChangeListener 。这使得无效和消息处理更容易。

By the way, you'd normally perform the validation with a normal Validator on the UIInput component or, in this particular case maybe better, a ValueChangeListener. This allows for easier invalidation and message handling.

这篇关于如何在bean的动作方法中的UIData组件内收集UIInput组件的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆