I am facing a weird issue with h:selectOneMenu component.
I am using an h:selectOneMenu in my JSF 2 application. I created an Arraylist of months in my controller class which is given to the h:selectOneMenu. The starting element of the dropdown is “Any” whose value is a blank string. The value of the h:selectOneMenu is tied to an object class variable “month”. Variable month is initialized as “” (empty string).
I have created a ValueChangeEvent on h:selectOneMenu. I have written a method changeMonth(event) in controller which is invoked on Value change event.
My issue is that this value change event is triggered when I click the submit button even though the value is not getting changed. This happens only when the dropdown is at “Any”. When I tried to get the values for the change in the changeMonth method I get the old value as “”(Blank string) and the new value as null.
Ideally the ValueChangeEvent should not be triggered. But since its changing from blank to null this is happening. Why does this happen? Is it an issue with the JSF 2 h: selectOneMenu component?
I am pasting my Controller code:
@ManagedBean
@SessionScoped
public class Controller {
private List monthList;
private ObjClass searchVO;
public List getMonthList() {
List<SelectItem> list = new ArrayList<SelectItem>();
list.add(new SelectItem("", "Any"));
for (int i = 1; i <= 12; i++) {
list.add(new SelectItem(String.valueOf(i), "Month"+i));
}
monthList = list;
return monthList;
}
/**
* @param monthList
* the monthList to set
*/
public void setMonthList(List monthList) {
this.monthList = monthList;
}
public ObjClass getSearchVO() {
if (searchVO == null) {
searchVO = new ObjClass();
}
return searchVO;
}
public void setSearchVO(ObjClass searchVO) {
this.searchVO = searchVO;
}
public void changeMonth(ValueChangeEvent changeEvent) {
PhaseId phaseId = changeEvent.getPhaseId();
String oldValue = (String) changeEvent.getOldValue();
String newValue = (String) changeEvent.getNewValue();
}
}
This is my Object Class:
public class ObjClass {
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
private String month="";
public ObjClass(String month) {
super();
this.month = month;
}
public ObjClass() {
}
}
And this is my xhtml form:
<h:form>
Dropdown example:
<h:selectOneMenu valueChangeListener="#{controller.changeMonth}"
onchange="submit();" id="month"
value="#{controller.searchVO.month}" title="Select Month">
<f:selectItems value="#{controller.monthList}" />
</h:selectOneMenu>
<br /><br />
<h:outputText value="#{controller.searchVO.month}"></h:outputText>
<h:commandButton value="Submit" action="result" />
<h:commandButton value="Reset" type="reset" />
</h:form>