Learn Java for Web Development

(Tina Meador) #1

376 CHAPTER 8: Play with Java and Scala



  1. }

  2. public static void create(Book book) {

  3. }

  4. public static void delete(Long id) {

  5. }

  6. }


   Lines 6 to 12: You create static methods to manage CRUD operations on Book.
Later you will implement these operations to store the books in a relational
database.

The Form and the View Template

A Form object encapsulates an HTML form definition, including validation constraints. To create a
form for the Book class, you need to add the following to your application controller:


static Form bookForm = Form.form(Book.class);


The previous code is used to define a play.data.Form that wraps an existing class. The type of
bookForm is Form.


You can add a constraint to the Book type using JSR-303 annotations. Listing 8-10 illustrates how to
make the label field required.


Listing 8-10. Adding the Validation Constraint


package models;


import java.util.*;


import play.data.validation.Constraints.*;


public class Book {


public Long id;


@Required
public String label;


...


Now you need to modify the view template to display the screen for creating the book and listing all
the books.


Templates are compiled as standard Scala functions. If you create a views/Application/index.scala.html
template file, Scala will generate a views.html.Application.index class that has a render() method.
Listing 8-11 shows a simple template.

Free download pdf