1

Given the following view-state and binding:

<view-state id="updatePartner" view="/partners/partnerForm" model="partner">
    <binder>
        <binding property="name" required="true" />
        <binding property="address" required="true" />
        <binding property="address2" />
        <binding property="city" required="true" />
        <binding property="state" required="true" />
        <binding property="zip" required="true" />
        <binding property="phone" required="true" />
    </binder>
    ...
</view-state>

I'm getting a Partner object with "" in address2. I want a null there.

How do I force a null instead of blank strings? I would like to avoid explicit POJO setters that coerce blank strings into nulls.

I looked at Converters, but those seem to convert from one type to another (i.e. String to Long, etc.) and I think it would create to extra work for the application if I created a Converter to convert all Strings to Strings and made it remove blank strings, and in addition, that could theoretically break other things that I don't want touched.

I've seen the StringTrimmerEditor option (https://stackoverflow.com/a/2977863/3810920), and I can see the InitBinder method getting called, but my POJO still has "" in address2.

Thanks!

Community
  • 1
  • 1
arnaldop
  • 333
  • 6
  • 17

1 Answers1

2

You can create a custom converter:

public class EmptyStringToNullConverter extends StringToObject {

    public EmptyStringToNullConverter() {
        super(String.class);
    }

    @Override
    protected Object toObject(String string, Class targetClass) throws Exception {
        return StringUtils.isNotBlank(string) ? string : null;
    }

    @Override
    protected String toString(Object object) throws Exception {
        return object.toString();
    }
}

then add in your ApplicationConversionService

addConverter("emptyToNullString", new EmptyStringToNullConverter());

then you can use:

<binding property="name" converter="emptyToNullString"/>
rptmat57
  • 3,643
  • 1
  • 27
  • 38
  • That sounds great! I was still hoping that there was an existing converter that I could leverage, even though yours is quite elegant! – arnaldop Apr 18 '16 at 15:44
  • I am still trying to figure it out myself. it's annoying to have to explicitly use a converter – rptmat57 Apr 18 '16 at 20:31