Convert h:selectBooleanCheckbox value between boolean and String

Tarun Sapra picture Tarun Sapra · Jun 15, 2011 · Viewed 17k times · Source

I have a backing bean containing a field creditCard which can have two string values y or n populated from the DB. I would like to display this in checkbox so that y and n gets converted to boolean.

How can I implement it? I can't use a custom converter as getAsString() returns String while rendering the response whereas I need a boolean.

Answer

BalusC picture BalusC · Jun 15, 2011

The <h:selectBooleanCheckbox> component does not support a custom converter. The property has to be a boolean. Period.

Best what you can do is to do the conversion in the persistence layer or to add extra boolean getter/setter which decorates the original y/n getter/setter or to just replace the old getter/setter altogether. E.g.

private String useCreditcard; // I'd rather use a char, but ala.

public boolean isUseCreditcard() {
    return "y".equals(useCreditcard);
}

public void setUseCreditcard(boolean useCreditcard) {
    this.useCreditcard = useCreditcard ? "y" : "n";
}

and then use it in the <h:selectBooleanCheckbox> instead.

<h:selectBooleanCheckbox value="#{bean.useCreditcard}" />