How to get the selected value of a Select One Choice or LOV in a bean.
The valueChangeEvent of the
Select One Choice valueChangeListener will return the index value of the selected item instead of its original value in the List. So, how to get the original value? Here is the solution to overcome the problem.
UI Code:
<af:selectOneChoice value="#{bindings.ManagerId.inputValue}" autoSubmit="true"
valueChangeListener="#{SecurityDemoBean.managerChangeListener}"
label="#{bindings.ManagerId.label}"
required="#{bindings.ManagerId.hints.mandatory}"
shortDesc="#{bindings.ManagerId.hints.tooltip}"
id="soc1">
<f:selectItems value="#{bindings.ManagerId.items}" id="si1"/>
</af:selectOneChoice>
UI Output:
Bean Code:
When user makes a selection, managerChangeListener will be called.
public void managerChangeListener(ValueChangeEvent valueChangeEvent) {
// Add event code here...
System.out.println("Selected Value from event:"+valueChangeEvent.getNewValue()+" ---- Selected Value:"+evaluateEL("#{bindings.ManagerId.items["+valueChangeEvent.getNewValue()+"].label}"));
System.out.println("Selected Value from EL :"+evaluateEL("#{bindings.ManagerId.items["+valueChangeEvent.getNewValue()+"].value}"));
}
public static Object evaluateEL(String el){
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elCtx = facesContext.getELContext();
ExpressionFactory expFactory =facesContext.getApplication().getExpressionFactory();
ValueExpression valExp =expFactory.createValueExpression(elCtx, el, Object.class);
return valExp.getValue(elCtx);
}
Output in the console:
Selected Value from event:98 ---- Selected Value:Julia
Selected Value from EL :98