0

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Danijel
  • 8,198
  • 18
  • 69
  • 133

1 Answers1

3

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(), not getNewLabel(). 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:


Unrelated to the concrete problem: the combination of a <h:selectOneMenu>, a valueChangeListener and onchange="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.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • But I copy-pasted this code from a sample that works ok. Hmmm... Is it possible that label and value in that sample are the same, and in my sample not? – Danijel Mar 19 '12 at 21:49
  • I don't know what sample you're talking about. But key point is that only the item value is been sent, not the item label. If they are the same or there is no label, then obviously you get the value as label :) – BalusC Mar 19 '12 at 22:43
  • Thanks BalusC. Could you explain the above 'then you'll either need to use it instead of option value while creating the select items'? I am unclear where this item creation is done? – Danijel Mar 20 '12 at 08:34