I am using the managedBean userHome in requestScope, in which the entity 'user' is going to be persist. The user has the leader column which is mapped in ManyToOne relation.My Code looks like this
@ManagedBean
@RequestScoped
public class UserHome {
    private User user = new User();
        // Getters and Setters
    private List<SelectItem> selectItems = new ArrayList<SelectItem>();
    public UserHome() {
        for(User user: availableLeaders) {
            selectItems.add(new SelectItem(user.getName(), user));
        }
    }
    public void persis();
}
User.java
public class User {
    @Id
    @Column
    private Integer id;
    @Column
    privat String name;
    @ManyToOne
    private User leader;
}
I am trying to get the value of this leader through h:selectOneMenu like this
<h:selectOneMenu value="#{userHome.user.leader}" converter="userConverter">
    <f:selectItems value="#{userHome.selectItems}"/>
</h:selectOneMenu>
My converter looks like this
@FacesConverter(forClass = User.class, value="userConverter")
public class UserConverter implements Converter {
    private  Map<String, User> userValues = new HashMap<String, User>();
    public UserConverter() {
        init();
    }
    @Override
    public Object getAsObject(FacesContext context, UIComponent component,
            String value) {
        return userValues.get(value);
    }
    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        System.out.println("RAJASEKARAN "+value);
        return ((User)value).getName();
    }
    public void init() {
        UserHome userHome = new UserHome();
        for(User user:userHome.availableLeaders()) {
            userValues.put(user.getName(), user);
        }
    }
}
While try to save the user I am getting the error UserEdit:j_idt18: Validation Error: Value is not valid
Adding to BalusC's answer: after the postback, you need to make sure that the User instances are either exactly the same ones as you used for rendering the select items, or that you implement equals for your User class.
The code doesn't show where availableLeaders comes from, but if this is fetched from a DB on-demand, then the converter will not convert to the exact same object instance that's in the list that JSF resolves via #{userHome.selectItems}.
After the conversion, JSF will check whether the converted instance can be found in that list using the equals() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With