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!

1 Answer 1

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"/>
Sign up to request clarification or add additional context in comments.

2 Comments

That sounds great! I was still hoping that there was an existing converter that I could leverage, even though yours is quite elegant!
I am still trying to figure it out myself. it's annoying to have to explicitly use a converter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.