0

エンティティ Post と Author を持つブログを考えてみましょう。Post と Author の間には ManyToOne の関係があります。

@Entity
public class Post extends Model {
  @Required
  public String subject;

  @ManyToOne
  @Required
  public Author author;

  //...
}

次に、ビューで:

@form(routes.Post.new()) {
  @inputText(postForm("subject"))
  @select(
    postForm("author.id"), 
    options(Author.options()), 
    '_label -> "Author",
    '_default -> "-- Select author --",
    '_showConstraints -> true
  )
  <input type="submit" value="Create" />
}

コントローラで aを使用してこのフィールドを検証するForm<Post>場合、form.hasErrors() を実行するときに Author フィールドの @Required 制約は無視されます。

このフィールドが必須であるとどのように言えますか?

4

1 に答える 1

1

そのような場合、フォームはデフォルトidAuthor(または選択されていない場合は空の文字列)を渡します。最速のソリューションは次のとおりです。

if (postForm.hasErrors()
        || form().bindFromRequest().get("author.id")==null
        || form().bindFromRequest().get("author.id").equals("")) {

    return badRequest(postAdd.render(postForm));
}

最終的に、Author オブジェクトに到達可能かどうかを検証し、そうでない場合はエラー メッセージを返すことができます。

Author authorRef =
     Author.find.ref(Long.valueOf(form().bindFromRequest().get("author.id")));

if (postForm.hasErrors() || authorRef == null) {
    return badRequest(postAdd.render(postForm));
}

編集もちろん、フィールドをまったく渡さない場合(たとえば@select{...}、ビューから削除する場合)、@Required制約はそれをキャッチします。

于 2012-08-31T07:54:03.640 に答える