2. Modify Code

Edit the generated Grails domain and controller classes. This will add fields and validation rules to the domain classes, and activate scaffolding in the controller classes. Grails' scaffolding automatically generates a controller and JSP pages that work with the associatd domain class.

First add a first name, last name, created, and list of addresses to Person. By assigning the hasMany field to [addresses:Address], this creates a relationship to Address with an addresses list variable. The constraints section is where validation rules can be set. All the fields are set to not allow null values.

Edit grails-app/domain/Person.groovy to match the code below.

Example 1. Person

                
class Person {

	String firstName
	String lastName
	List<Address> addresses
	Date created

	static hasMany = [addresses:Address]

    static constraints = {
        firstName(nullable:false)
        lastName(nullable:false)
        created(nullable:false)
    } 	
        
}
                
            

Next, add the basic fields to Address and define that it is the many part of a one-to-many relationship to Person by assigning the belongsTo field to Person.

Edit grails-app/domain/Address.groovy to match the code below.

Example 2. Address

                
class Address {

    String address
    String city
    String state
    String zipPostal
    String country
    Date created
    
    static belongsTo = Person

    static constraints = {
        address(nullable:false)
        city(nullable:false)
        state(nullable:false)
        zipPostal(nullable:false)
        country(nullable:false)
        created(nullable:false)
    }

}
                
            

Now that the domain objects are setup, the controllers will be set to use Grails' scaffolding. This will autogenerate the controller interface and basic JSP pages. The scaffold variable just needs to be set to true and Grails will handle everything else. The PersonController is automatically associated with the Person domain class based on default naming conventions.

Edit grails-app/controllers/PersonController.groovy to match the code below.

Example 3. PersonController

                
class PersonController {

   def scaffold = true
   
}
                
            

Activate scaffolding for the AddressController.

Edit grails-app/controllers/AddressController.groovy to match the code below.

Example 4. AddressController

                
class AddressController {

   def scaffold = true
   
}