how to get value from ?

2019-03-02 05:52发布

问题:

i want to get the value from . i tryed this code but it doesn't work :

<h:form>
        <h:outputLabel value="départements : "/>
        <h:selectOneMenu value="#{departementController.selected.id}" onchange="submit()" immediate="true">
            <f:valueChangeListener type="Controller.Listener.DepartementValueListener"/>
            <f:selectItems value="#{departementController.itemsAvailableSelectOne}"/>
        </h:selectOneMenu>

        <h:outputLabel value="nouvelle valeur : "/>

        <h:inputText value="#{departementController.comboBox}" id="dep"/>
    </h:form>

the controller :

 //departement change listener
private String comboBox;

public String getComboBox() {
    return comboBox;
}

public void setComboBox(String comboBox) {
    this.comboBox = comboBox;
}

public void departementChangeListener(ValueChangeEvent e) {
    // Skip validation of non-immediate components and invocation of the submit() method.
    FacesContext.getCurrentInstance().renderResponse();
    this.comboBox = e.getNewValue().toString();}

sourceId=j_idt7:j_idt9[severity=(ERROR 2), summary=(j_idt7:j_idt9 : erreur de validation. La valeur est incorrecte.), detail=(j_idt7:j_idt9 : erreur de validation. La valeur est incorrecte.)]

回答1:

You've after all 2 problems.

First, the error "erreur de validation. La valeur est incorrecte" which is the French translation of "Validation Error: Value is not valid" means that the submitted value doesn't equals() any one of the available items in <f:selectItems>. Your code is not complete enough to point out the root cause, but I guess that you've a List<Department> there in <f:selectItems value> and thus every item is Department, but you're trying to set it as a String value of id instead of as Department. This is not right. You need to supply a converter between Department and String and use #{departementController.selected} instead.

Something like this:

<h:selectOneMenu value="#{bean.selectedDepartment}">
    <f:selectItems value="#{bean.availableDepartments}" />
</h:selectOneMenu>

with

private Department selectedDepartment;
private List<Department> availableDepartments;

And a @FacesConverter which converts between Department and its unique String representation.

Your second problem is that you seem to be focusing too much on JSF 1.x targeted examples as to populating another field on change of the dropdown. You're using a rather clumsy/hacky JSF 1.x workaround for that. In JSF 2.x you can just use <f:ajax> for this.

<h:selectOneMenu value="#{bean.selectedDepartment}">
    <f:selectItems value="#{bean.availableDepartments}" />
    <f:ajax listener="#{bean.changeDepartment}" render="inputId" />
</h:selectOneMenu>
<h:inputText id="inputId" value="#{bean.input}" />

with

public void changeDepartment() {
    input = selectedDepartment.getId();
}

See also:

  • Our selectonemenu wiki page