0

How do I validate required fields on a form within the controller? For example, my entity has the creation_date field, but I do not put this field within the form in the view, as it is required I need to set it out of view, ie, within the controller. Does anyone have any examples of how to do this?

Thanks

Edit: I'm sorry, I did not make myself clear. I have a field in my entity annotated with @NotNull and I just need to fill value in controller (task.setCreationDate(new Date())). The field doesn't need to be validated in view scope. Example:

public static Result newTask() {
    Form<Task> form = taskForm.bindFromRequest();
    if (form.hasErrors()) {
        return badRequest("Error");
    } else {
        Task task = form.get();
        task.setCreationDate(new Date());
        taskDAO.save(task);
        return redirect(routes.Application.tasks());
    }
}

In the code above, the form isn't validated (returns hasErrors()).

2 Answers2

0

I think you shouldn't annotate this field as required if you haven't a form input for it. Instead you will set this field after bindFromRequest and before saving the entity.

But if you really want to do it, maybe something like this could work:

Form<MyEntity> myEntityForm = Form.form(MyEntity.class).bindFromRequest();
myEntityForm.data().put("creation_date", ...);
user1664823
  • 101
  • 4
  • Thanks for the reply, but I guess I was not very clear in the question. The field is @NotNull in my entity, but it isn't a required field on the form and I will fill the field in the controller, but when I retrieve the form, the same isn't validated (returns hasErrors ()). I edited my question and put an example. – Paulo Kinzkowski Junior Aug 06 '13 at 18:03
  • If you are always setting the value yourself in the controller then just remove the `@NotNull` annotation from the field. – estmatic Aug 06 '13 at 19:54
0

Having field annotated as @NotNull is handy because it propagates the constrain down to DB level.

I would rather stick with one of these two approaches:

  1. Add public String validate() method to your Task class. It should return null in case of no errors and error string in case of errors.

  2. Implement your custom validator. Example is here: How to create a custom validator in Play Framework 2.0?

Community
  • 1
  • 1
Leo
  • 2,097
  • 21
  • 35