I am having problems with ValueChangeListener attached to a dropdown list.
Here is the code:
<h:selectOneMenu
value = "#{MultiFileSelectMgmtBean.selectedLocationName}"
valueChangeListener = "#{MultiFileSelectMgmtBean.LocationChangeEvent}"
onchange = "submit();"
>
<f:selectItems
value = "#{MultiFileSelectMgmtBean.locationsListItems}">
</f:selectItems>
</h:selectOneMenu>
And here is the backing bean:
protected List<SelectItem> locationsListItems;
...
public void LocationChangeEvent( ValueChangeEvent vce ) throws Exception
{
selectedLocationName = (String) vce.getNewValue();
}
The problem is that ‘selectedLocationName’ gets a “11” or “13” value, even the dropdown list is populated with two strings “LocationTest1” and “LocationTest2”.
What could be the problem with vce.getNewValue?
The submitted value of the dropdown list is the option value, not the option label as you seem to think. Note that the method is also called
getNewValue(), notgetNewLabel(). The option labels are not sent over HTTP from client to server by the HTML form submit. There’s no way to extract them from the HTTP request.If you really need the option label instead of the option value for some unclear reason, then you’ll either need to use it instead of option value while creating the select items, or to have a mapping of all option labels associated with the option values somewhere, so that you can get the label by the value from this mapping. The chance is big is that you already have this sort of mapping in your bean, otherwise you wouldn’t be able to populate the
<f:selectItems>value 🙂See also:
<h:selectOneMenu>tag wiki pageUnrelated to the concrete problem: the combination of a
<h:selectOneMenu>, avalueChangeListenerandonchange="submit()"indicates that you’re using a JSF 1.x specific hack in order to achieve the functional requirement of populating another dropdown or fields based on the change of the dropdown. Since you seem to be already using JSF 2.x, I recommend you to forget about this approach at all and just use<f:ajax listener>instead. The aforelinked wiki page contains one example.