Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Wednesday, September 14, 2011

Lean Server Side Validation with the Play! Framework

In a previous post, I wrote about validating a Play! Framework form using flash scope variables. A downside of that approach is that extra code is needed to marshall and unmarshall the Model into these variables.  This post removes the flash variables and is dependent on only the domain object.

For forms that won't hit the size limit of a cookie (4k), you can save the form variables off to flash-scoped copies for re-display.  See this post for an example.  A reader, opensas, wrote a helpful comment that referenced a technique that obviates the need for flash variables.

Model

A central theme in the Play! Framework is to use your domain objects throughout your application.  The domain objects extend Generic Model which makes them persistable.  The domain objects will contain business logic, possibly referencing other Models.  The domain objects can also be used on the front-end to transport form variables.

This includes server-side validation logic.  In the following Controller method, a Model "Tutorial" is retrieved from the database if an id is present.

Basic GET Form Controller Handling Blank and Filled
 This method is also used if an id is not present: a blank form.  The method adds some lists to the form which are used in drop-downs.

 When the form is submitted, the method saveTutorial() is invoked.  Play! creates a Tutorial object which is filled with form variables.  Two validation() calls are made.  If the form is not valid, some lists are gathered and passed along to a render() call.

Controller Method Supporting Form POST
 In the validation.hasErrors() code block, there isn't a reference to the flash scope.  The errors data structure was set up in the validation calls and will be available to the re-displayed form.

The @showTutorial in the render call is a reference to a template rather than the method.  There is a file showTutorial.html that will be called from saveTutorial().

Here is the re-worked view code.  Note that the flash.tutorial_title_tx has been replaced with tutorial.tutorial_title_tx.

View Code

The URLs

As mentioned in opensas' comment in the post about flash variables, there is an inconsistency in the URLs.  saveTutorial().  Upon a validation error, the /savetutorial URL is displayed in the browser instead of the /showtutorial which occurs on a successful submission.  The flash variable version invokes the "right" controller so the URLs are consistent.

But given that I don't have to re-define each Model as a set of flash variables, I think this is the better approach.  Many thanks to opensas.

No comments:

Post a Comment