Play! FrameworkのTutorialで、Validate失敗時、入力した値を戻す

今週のはじめより、Java(+Python)で作られたPlay frameworkの勉強をはじめました。2004年にRuby on Rails 1.0を知った時と同じ衝撃を感じています。こいつ、できるぞと。また、Java 1.4.2以降はRubyを始めてしまったので、今更かもしれませんがアノテーションとか新鮮で、ワクワクしています。まだ調べていないのですが、日本語メール(シフトJISにただ変換すればおしまい?)やマイグレーション(play migrateとかないのかな...)はどうなるのかな。

Play! frameworkのTutorialで、コメント投稿時(postComment)にValidationで失敗すると、元のページに戻りますが、テキストフィールドなどに入力した値が消えてしまいます。そこで、postCommentメソッド(Application.java)でValidationに失敗したら、renderの引数に入力した値を渡せばいいのですが...

if(Validation.hasErrors()) {
    render("Application/show.html", post, author, content); 
}

テキストフィールドとテキストエリアの2つしかないので、これでもよいのかなと思ったのですが、あまり美しくない。Commentクラスのインスタンスを渡してやるか。

if(Validation.hasErrors()) {
    Comment invalidComment = new Comment(post, author, content);
    render("Application/show.html", post, invalidComment); 
}

でも、CommentクラスのpostやpostedAt変数は必要ないので、Commentモデル(Comment.java)にもう一つコンストラクタを用意。

public Comment(String author, String content) {
    this.author = author;
    this.content = content;
}

そうすれば、

if(Validation.hasErrors()) {
    Comment invalidComment = new Comment(author, content);
    render("Application/show.html", post, invalidComment, randomID); 
}

と余計なpost変数を引数で渡さず、postedAt変数に現在日時は代入されない。viewの方は(show.html)、

<p>
    <label for="author">Your name:</label>
    <input type="text" name="author" id="author" value="${invalidComment?.author}" />
</p>
<p>
    <label for="content">Your message:</label>
    <textarea name="content" id="content">${invalidComment?.content}</textarea>
</p>

Play! frameworkのTutorialは、本当に良く出来ていると思う。日本語版でないかな...