How to set converter properties for each row/item of h:dataTable/ui:repeat?

Solution 1:

To the point, you expected that the converter's properties are set every time a datatable row is rendered. This is indeed not true. JSF will create only one converter instance per component when the view is to be built, it will not create/reset the converter each time the row is rendered.

There are several ways to get it to work.

  • Pass the dynamic attributes as <f:attribute> of the component and let the Converter intercept on that. You can find an example here: JSF convertDateTime with timezone in datatable. This can then be used as

    <h:outputText value="#{item.balanceDate}">
        <f:converter converterId="isoDateTimeConverter" />
        <f:attribute name="pattern" value="#{item.pattern}" />
    </h:outputText>
    

  • Use an EL function instead of a Converter. You can find an example here: Facelets and JSTL (Converting a Date to a String for use in a field). This can then be used as

    <h:outputText value="#{mh:convertIsoDate(item.balanceDate, item.pattern)}" />
    

  • Bind the converter and datatable's DataModel as a property of the same managed bean. This way you will be able to set the converter's properties based on the row data before returning it. Here's a basic kickoff example based on standard JSF components and standard DateTimeConverter (it should work equally good on PrimeFaces components and with your custom converter):

    <h:dataTable value="#{bean.model}" var="item">
        <h:column>
            <h:outputText value="#{item.date}" converter="#{bean.converter}" />
        </h:column>
    </h:dataTable>
    

    with

    @ManagedBean
    @ViewScoped
    public class Bean implements Serializable {
    
        private List<Item> items;
        private DataModel<Item> model;
        private DateTimeConverter converter;
    
        @PostConstruct
        public void init() {
            items = Arrays.asList(
                new Item(new Date(), "dd-MM-yyyy"), 
                new Item(new Date(), "yyyy-MM-dd"), 
                new Item(new Date(), "MM/dd/yyyy"));
            model = new ListDataModel<Item>(items);
            converter = new DateTimeConverter();
        }
    
        public DataModel<Item> getModel() {
            return model;
        }
    
        public Converter getConverter() {
            converter.setPattern(model.getRowData().getPattern());
            return converter;
        }
    
    }
    

    (the Item class is just a bean with two properties Date date and String pattern)

    this results in

    23-09-2011
    2011-09-23
    09/23/2011


  • Use OmniFaces <o:converter> instead. It supports render time evaluation of EL in the attributes. See also the <o:converter> showcase example.

    <h:outputText value="#{item.balanceDate}">
        <o:converter converterId="isoDateTimeConverter" pattern="#{item.pattern}" />
    </h:outputText>
    

Solution 2:

The above excellent (as always) answer from BalusC is comprehensive but didn't quite hit my exact requirement. In my case, I need to bind a Converter to each iteration in a ui:repeat. I need a different Converter depending on each item being repeated. The answer did point me in the right direction, though, so I thought it worth sharing my solution in case it helps anyone else.

I use a Converter that delegates all it's work to another Converter object specified in the attribute, as in the first of BalusC's answers. Note that this doesn't help at all if you wish to use converters with parameters, it's aimed at the situation where you would want to bind a Converter to a property of a repeating object.

Here's the delegating Converter. It's also a Validator, which works in exactly the same way.

// package and imports omitted for brevity
@FacesConverter(value="delegatingConverter")
@FacesValidator(value="delegatingValidator")
public class Delegator implements Converter, Validator {

    // Constants ---------------------------------------------------------------
    private static final String CONVERTER_ATTRIBUTE_NAME = "delegateConverter";
    private static final String VALIDATOR_ATTRIBUTE_NAME = "delegateValidator";

    // Business Methods --------------------------------------------------------
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, 
            String value) throws ConverterException {
        return retrieveDelegate(component, Converter.class, CONVERTER_ATTRIBUTE_NAME)
                .getAsObject(context, component, value);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, 
            Object value) throws ConverterException {
        return retrieveDelegate(component, Converter.class, CONVERTER_ATTRIBUTE_NAME)
                .getAsString(context, component, value);
    }

    @Override
    public void validate(FacesContext context, UIComponent component, 
            Object value) throws ValidatorException {
        retrieveDelegate(component, Validator.class, VALIDATOR_ATTRIBUTE_NAME)
                .validate(context, component, value);
    }
    
    private <T> T retrieveDelegate(UIComponent component, Class<T> clazz,
            String attributeName) {
        Object delegate = component.getAttributes().get(attributeName);
        if (delegate == null) {
            throw new UnsupportedOperationException("No delegate was specified."
                    + "  To specify, use an f:attribute tag with: name=\"" 
                    + attributeName + "\"");
        }
        if (!(clazz.isAssignableFrom(delegate.getClass()))) {
            throw new UnsupportedOperationException("The specified delegate "
                    + "was not a " + clazz.getSimpleName() + " object.  " +
                    "Delegate was: " + delegate.getClass().getName());
        }
        return (T) delegate;
    }
}

So now where I would wish to use this code within my ui:repeat, which won't work:

<h:outputText value="#{item.balanceDate}">
    <f:converter binding="#{item.converter} />
    <f:validator binding="#{item.validator} />
</h:outputText>

I can instead use this code, which works OK:

<h:outputText value="#{item.balanceDate}">
  <f:converter converterId="delegatingConverter"/>
  <f:validator validatorId="delegatingValidator"/>
  <f:attribute name="delegateConverter" value="#{item.converter}"/>
  <f:attribute name="delegateValidator" value="#{item.validator}"/>
</h:outputText>

Assuming that the repeating item has a public Converter getConverter() method and similar for the Validator.

This does have the advantage that the same Converters or Validators that are used elsewhere can be re-used without any changes.