Creating a null-capable converter

Here's a methodology for creating converters that support null-capable and disabled SelectItems that might be of interest to others.

Example usage (hand-typed):

SelectItem selectItems[] = new SelectItem[items1List.size() + items2List.size() + 3];
int index = 0;
selectItems[index++] = new SelectItem(ConverterOptions.NULL_OPTION_VALUE, NO_ITEM_SELECTED);
selectItems[index++] = new SelectItem(ConverterOptions.DISABLED_OPTION_VALUE, ITEM1_LIST_HEADER);
for (int index1 = 0; index1 < itemsList.size(); ++index1) {
    selectItems[index++] =  (SelectItem )items1List.get(index1);
} 
selectItems[index++] = new SelectItem(ConverterOptions.DISABLED_OPTION_VALUE, ITEM2_LIST_HEADER);
for (int index2 = 0; index2 < itemsList.size(); ++index2) {
    selectItems[index++] =  (SelectItem )items2List.get(index2);
}

return selectItems;

Converter code:

public final static String DISABLED_OPTION_VALUE = "jsf.converter.DISABLED_OPTION_VALUE";
public final static String NULL_OPTION_VALUE = "jsf.converter.NULL_OPTION_VALUE";


public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException
{
	if (null == value)  return null;
    if (ConverterOptions.DISABLED_OPTION_VALUE.equals(value))  return ConverterOptions.DISABLED_OPTION_VALUE;  // should never be executed
    if (ConverterOptions.NULL_OPTION_VALUE.equals(value))  return null;
            
    return // your getAsObject implementation;
}

public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException
{
	if (null == value)  return null;
    if (ConverterOptions.DISABLED_OPTION_VALUE.equals(value))  return ConverterOptions.DISABLED_OPTION_VALUE;
    if (ConverterOptions.NULL_OPTION_VALUE.equals(value))  return ConverterOptions.NULL_OPTION_VALUE;

    return // your getAsString implementation;
}

Approach for InputText

An other approache for InputText components can be found at http://jroller.com/page/stritti?entry=jsf_stringconverter_for_null_values

  • No labels