Announcement Announcement Module
No announcement yet.
Forms: converting empty input fields to null... Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Forms: converting empty input fields to null...

    Hi all,

    When some input text fields are left blank in a form, the command object seems to be populated with some empty strings. If I want to set null values in the database, is there a mean in Spring to tell that we would like null values instead of empty strings in the command object that is populated after a form submittal ? It would be handy instead of checking every field manually...


  • #2
    I ran into this problem as well, and have been doing this kind of thing in the String setters of my domain objects (this example is from my "Person" class):

       * @param homePhone The homePhone to set.
      public void setHomePhone(String homePhone) {
        this.homePhone = StringUtils.trimToNull(homePhone);
    ... where StringUtils is from commons-lang-2.0.

    I'm glad you asked the question however, as I've just realised another possible solution. If your form controller extends SimpleFormController, simply override the initBinder() method and register an org.springframework.beans.propertyeditors.StringTr immerEditor either for all String fields (by leaving out the field name when calling registerCustomEditor()) or just the fields that you want converted to null.

    Which approach you take depends on:
    (1) how lazy you are, i.e. you can just register the custom editor once for each form that contains strings, and you're done,
    (2) whether you regard the conversion of empty strings to nulls as business logic (in which case it should be in your domain object like my example above) or as presentation logic (i.e. you consider an empty string simply to be the HTML representation of a null domain value, in which case you would use the "custom property editor" approach)
    (3) whether you want your domain objects to behave consistently regardless of how they are populated (remembering that this can happen not only when a form is submitted, but also when loading data from a database, which might have empty strings for null values, or even from some other client type (standalone app or web service) that might come along in the future)

    I think I'll leave my string conversion in the domain object for the last reason, and just accept that this means touching every String setter I generate. But I'd be interested in what other people think too.

    Hope this helps,