Wednesday, February 20, 2013

Working With Nested Forms with Play 2.1

When creating nested forms and modifying input parameters into a Play 2.1 application seems simple, in many occasions it can be confusing. Here is an application with a model named Hedger which has a object named MarketData. In here I will try to explain the following:
  • How to handle a nested form inside the controller
  • How to configure the nested form in the view page
  • Create custom validations with Play 2.1 form

The first thing that we will show is the model objects - Hedger and MarketData

Now, we will create the form inside the controller

Noticed that there is a "sixMonth" and a "year" field in the form. These two fields are bind with the MarketData object. Therefore, we need to bind the input parameters into the case class. However, the object accepts Double and the form has "text". To handle this, we used a custom validation by using "text.verifying". The verifying contains two parameters:

  • Error message
  • Boolean validation that there is an error - isInvalid

The Hedger.validateDouble has the following code

You can also do the match inside the form, but I did this to make the code cleaner and to show that you can do the checking inside the object

When binding the object, you need to take care of the "apply" and "unapply". In the apply section, you need to show the mapping of the Hedger object, but since this is a nested form, you also need to take care of the MarketData as we saw in the previous code.

Here is the view page for the application:

No comments:

Post a Comment