Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
865 views
in Technique[技术] by (71.8m points)

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

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());
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...