Showing posts with label binding date. Show all posts
Showing posts with label binding date. Show all posts

Thursday, February 27, 2014

Binding a Grails date from params in a controller

Add the following lines in 'Config.groovy' file


grails.databinding.trimStrings=true
grails.databinding.convertEmptyStringsToNull=true
grails.databinding.dateFormats = ['yyyy-MM-dd HH:mm:ss.S', 'yyyy-MM-dd', "yyyy-MM-dd'T'hh:mm:ss'Z'"]

First line triming all string values on data binding to domain instance.
Second line convert all empty string to null.
And third line accept the date formats provided to convert it to date.

Or you can use those as following:


package com.pkm.test.domains

import org.grails.databinding.BindingFormat

class TestOne {
    Long id
    String name;
    String display;
    @BindingFormat("yyyy-mm-dd")
    Date created;

    static constraints = {
        display(nullable: true)
    }
}

And from controller


params.name = "YES-Pritom K Mondal";
params.display = " ";
params.created = "2014-02-27";
TestOne testOne = new TestOne();
DataBindingUtils.bindObjectToInstance(testOne, params)
testOne.save(failOnError: true);

Will create a following row in the table


Field 'display' is null because value from controller: ' ' first trim() and then convert empty string to null according to Config.groovy settings above.