I'm populating a <p:selectOneMenu/>
from database as follows.
<p:selectOneMenu id="cmbCountry"
value="#{bean.country}"
required="true"
converter="#{countryConverter}">
<f:selectItem itemLabel="Select" itemValue="#{null}"/>
<f:selectItems var="country"
value="#{bean.countries}"
itemLabel="#{country.countryName}"
itemValue="#{country}"/>
<p:ajax update="anotherMenu" listener=/>
</p:selectOneMenu>
<p:message for="cmbCountry"/>
The default selected option, when this page is loaded is,
<f:selectItem itemLabel="Select" itemValue="#{null}"/>
The converter:
@ManagedBean
@ApplicationScoped
public final class CountryConverter implements Converter {
@EJB
private final Service service = null;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
try {
//Returns the item label of <f:selectItem>
System.out.println("value = " + value);
if (!StringUtils.isNotBlank(value)) {
return null;
} // Makes no difference, if removed.
long parsedValue = Long.parseLong(value);
if (parsedValue <= 0) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Message"));
}
Country entity = service.findCountryById(parsedValue);
if (entity == null) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_WARN, "", "Message"));
}
return entity;
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Message"), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return value instanceof Country ? ((Country) value).getCountryId().toString() : null;
}
}
When the first item from the menu represented by <f:selectItem>
is selected and the form is submitted then, the value
obtained in the getAsObject()
method is Select
which is the label of <f:selectItem>
- the first item in the list which is intuitively not expected at all.
When the itemValue
attribute of <f:selectItem>
is set to an empty string then, it throws java.lang.NumberFormatException: For input string: ""
in the getAsObject()
method even though the exception is precisely caught and registered for ConverterException
.
This somehow seems to work, when the return
statement of the getAsString()
is changed from
return value instanceof Country?((Country)value).getCountryId().toString():null;
to
return value instanceof Country?((Country)value).getCountryId().toString():"";
null
is replaced by an empty string but returning an empty string when the object in question is null
, in turn incurs another problem as demonstrated here.
How to make such converters work properly?
Also tried with org.omnifaces.converter.SelectItemsConverter
but it made no difference.
See Question&Answers more detail:
os