How to collect values of an UIInput component inside an UIData component in bean's action method?

不羁的心 提交于 2019-11-30 06:04:13

问题


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>

Here's the backing bean code:

private UIData table;
private UIInput input;

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

回答1:


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.

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;
    }
});

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.



来源:https://stackoverflow.com/questions/10665385/how-to-collect-values-of-an-uiinput-component-inside-an-uidata-component-in-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!