0

Consider a blog with the entities Post and Author. There is a ManyToOne relation between Post and Author:

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

  @ManyToOne
  @Required
  public Author author;

  //...
}

Then, in the view:

@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" />
}

When validating this field using a Form<Post> in a controller, the @Required constraint for the Author field is ignored when doing form.hasErrors().

How can I say that this field is required?

Markus
  • 809
  • 5
  • 10

1 Answers1

1

Your form by default passes id of the Author (or empty String if not selected) in such case your fastest solution will be:

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

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

eventually you can validate if Author object is reachable and return the error message if is not:

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

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

Edit Of course if you will not pass the field at all (for an example you'll remove the @select{...} from your view) the @Required constraint will catch that.

biesior
  • 55,576
  • 10
  • 125
  • 182
  • I've considered this, and of course this is a viable solution. However, this couples the controller too tightly to the model, and adds duplication for each field. Shouldn't this be a built-in feature in Play? – Markus Aug 31 '12 at 08:21
  • With this approach you don't need to set constraint in the model for relation field. Optionally can also search the web for writing custom validator ie http://stackoverflow.com/q/8115106/1066240 anyway I prefer my second suggestion - checking the ref in the controller, especially when using single action for different kinds of data saving. If you think that's missing feature you can send a suggestion to the Play's Lighthouse or pull request on the github – biesior Aug 31 '12 at 08:39