LoginSignup
2
2

More than 5 years have passed since last update.

[Grails]データバインディング(日付編)

Posted at

前提条件

  • アプリケーション名は bindingtest
  • ローカルホストで動作させる
  • ポートは 8080

日付のバインディング

例えば 19850220 (1985年2月20日)というString型の日付をフォームから受け取り、ドメインのDate型のプロパティに渡す場合。
態々コントローラの中などでStringからDateに変換して・・・なんてする必要はない。
ドメインの対象のDate型プロパティに @BindingFormat とういアノテーションを利用するだけ。

Hoge.groovy
package bindingtest
import org.grails.databinding.BindingFormat
class Hoge {

    String name
    Integer age
    @BindingFormat('yyyyMMdd')
    Date birthDate

    static constraints = {
    }
}
HogeController.groovy
package bindingtest

class HogeController {

    def dateTest() {
        def hoge = new Hoge(params)
        if (hoge.hasErrors()) {
            render hoge.errors.fieldErrors
        } else {
            render hoge.birthDate
        }
    }
}

これで、http://localhost:8080/bindingtest/hoge/dateTest/?name=koji&age=29&birthDate=19850220とうURLにアクセスすると、birthDateの値がちゃんとドメインのDate型変数birthDateに格納される。

データがドメインにバインディングされる際に、birthDateは yyyyMMdd という形式に合致しているかどうか自動的にチェックされ、Date型に変換され、格納される。

もしもDate型に変換できない場合は、errorsプロパティにエラーが格納される。

なお、yyyyMMddは言い換えるとただの8桁の数字となる。
つまり、渡された値がヨーロッパ形式で、20021985(20日02月1985年)だった場合、合計8桁の数字、という形式は保たれているわけなので、それをドメイン側は単純にyyyyMMdd(2002年19月85日)として解釈し、変換する。その結果、Date型には2003年8月23日が格納されることになる。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2