TomahawkPhant
TomahawkPhant

Reputation: 1160

Inputs in Play! for date and time?

I need to have 2 inputs in my form, one for date and one for time. In my model it is just one property of type java.util.Date. What is the best practice to handle generating the html and binding the input fields to the date property in the model using Play framework 2?

Note, if I use field constructors, I can't lay out the form the way I need to. I want a label on the first line, the 2 inputs on the second line, and validation errors on the third line. Should I just use raw html instead? If I do, will I still have access to validation errors and constraints?

Upvotes: 2

Views: 567

Answers (1)

Marius Soutier
Marius Soutier

Reputation: 11274

It'd be certainly easier to bind if you were using two separate fields in your model. One idea would be to create an intermediate class which binds to the form submission.

// Controller

public static class FormSubmission {
  public Date date;
  public Date time;
}

public static Result submitForm() {
  Form<FormSubmission> filledForm = form(FormSubmission.class).bindFromRequest();
  if (filledForm.hasErrors()) {
    return badRequest();
  } else {
    ModelClass model = new ModelClass(); // fetch first if you update
    // Copy all values from form submission to the model
    model.dateAndTime = combineDateAndTime(filledForm.get().date, filledForm.get().time);
  }
  return ok();
}

// View
@(form: Form[FormSubmission])
...

(I know this doesn't help, but tasks like this are extremely trivial in Scala.)

Upvotes: 3

Related Questions