Seam's Character to Boolean converter
braddm7 Apr 7, 2008 11:22 AMHello,
I have a JPA entity property that is of a primitive char(1) datatype, i.e. it returns a 'Y' or an 'N'. This field in the UI is represented as a boolean checkbox.
I created a Seam's converter which for some reason invoke only the 'getAsString' method of the javax.faces.convert.Converter interface. Here is a part of the Facelet:
<h:selectBooleanCheckbox value="#{someEntity.somePrimitiveChar}">
<f:converter converterId="charToBooleanConverter" /> </h:selectBooleanCheckbox>
The initial UI rendering is fine and in debug mode the checkbox is managed by the converter's 'getAsString' method. When the form is submitted it does not enter the 'getAsObject' method. Here is the converter itself.
package com.my.domain.converters; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.ConverterException; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.faces.Converter; import org.jboss.seam.annotations.intercept.BypassInterceptors; @Name("charToBooleanConverter") @BypassInterceptors @Converter public class CharToBooleanConverter implements javax.faces.convert.Converter { /** Default construction */ public CharToBooleanConverter() { } public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException { if (value == null || value.trim().length() == 0) return new Character('N'); Character toReturn = (value.equalsIgnoreCase("true")) ? 'Y' : 'N'; return toReturn; } public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException { String toReturn = "false"; if (value == null) { return toReturn; } if (value instanceof Boolean) { toReturn = (((Boolean) value) == true) ? "true" : "false"; } else if (value instanceof Character) { char toChar = ((Character) value).charValue(); toReturn = (toChar == 'Y' || toChar == 'y') ? "true" : "false"; } return toReturn; } }
I appreciate your help. Thanks.