On my page I have a drop down whose values are populated based on an enum and the selection sets the value of the enum as well . I now have requirement to display text like “Please select a Value” in the drop down and that is not present in enum.
It is also possible for user to not select any value from drop down .
How can a populate selectOne with this additional text without modifying enum and handle it in the managed bean if user does not select a value (which is legal for user to do so). I have tried various combinations but nothing worked for me .
Here is what I have working which is standard dropdown list populated with different values enum just a standar way.
This is enum here
public enum Fruit {
APPLE("Apple"), ORANGE("Orange");
private String label;
Fruit(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
A Managed Bean
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.model.SelectItem;
@ManagedBean
public class Simplebean {
private Fruit selectedFruit;// How would this work if the value is not valid enum .
private List<SelectItem>fruits = new ArrayList<SelectItem>();
@PostConstruct
public void init(){
for (Fruit fruit : Fruit.values()){
fruits.add(new SelectItem(fruit,fruit.getLabel()));// How to add a value not part of enum.
}
}
public List<SelectItem> getFruits() {
return fruits;
}
public void setFruits(List<SelectItem> fruits) {
this.fruits = fruits;
}
public Fruit getSelectedFruit() {
return selectedFruit;
}
public void setSelectedFruit(Fruit selectedFruit) {
this.selectedFruit = selectedFruit;
}
}
In XHTML
<h:selectOneMenu value="#{simplebean.selectedFruit}">
<f:selectItems value="#{simplebean.fruits}" />
</h:selectOneMenu>
You can do it as Luggi wrote, but add a the
noSelectionOptionto the additional<f:selectItem>. And a s suggestion – you don’t need to define the selectItem ListList<SelectItem>fruitsanymore on the backing bean, you can do it this way:And the backing bean without fruits selectItems: