0

I am trying to use an converter for custom objects, that are used in a primefaces' selectCheckboxMenu.

This is the JSF part:

<p:outputLabel value="#{msg.cars}: " for="cars" />
<p:selectCheckboxMenu id="cars"
    value="#{controller.selected.cars}"
    converter="carConverter" label="#{msg.cars}"
    filter="true" filterMatchMode="startsWith"
    panelStyle="width:200px">
    <f:selectItems
        value="#{controller.available.cars}" />
    <f:converter converterId="carConverter" />
</p:selectCheckboxMenu>

And this is my converter:

@FacesConverter("carConverter")
public class CarConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String newValue) {
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object object) {
        if (object == null) {
            return "";
        }
        if (object instanceof Car) {
            Car car = (Car) object;
            String name = car.getName();
            return name;
        } else {
            throw new ConverterException(new FacesMessage(object + " is not a valid car"));
        }
    }
}

getAsString() returns the correct String. But the selectCheckboxMenu still lists the objects and not the Strings.

Am I missing something?

John
  • 795
  • 3
  • 15
  • 38

1 Answers1

1

If you need to show the car name in checkboxMenu label you have to use the selectItems' itemLabel attribute

<p:outputLabel value="#{msg.cars}: " for="cars" />
<p:selectCheckboxMenu id="cars"
    value="#{controller.selected.cars}"
    converter="carConverter"
    filter="true" filterMatchMode="startsWith"
    panelStyle="width:200px">
    <f:selectItems value="#{controller.available.cars}" var="car" itemLabel="#{car.name}" itemValue="#{car}"/>
</p:selectCheckboxMenu>

BTW don't declare two converters (one via converter attribute and the other via f:converter), and override correctly the getAsObject method (it's needed during the Apply Request Values phase). Check the docs for the details

SiMag
  • 586
  • 2
  • 8