tags:

views:

275

answers:

3

What does person.properties = params do?

+2  A: 

Well, the short answer is that it matches any key in the params map with the properties of the person object, assigning the value in the params map to the property that matches.

example: Let's say params.id=156 and person has a member property named id. After this call, person.id would equal 156.

Some notes:

  • If there are keys in params that don't match properties in person, that's ok, it just won't do anything with those.
  • If there are properties in person that don't have keys in params? Also ok, it'll skip those too.
  • This is also very similar to creating a new Person via "new Person( params )" or calling "bindData( person, params )".
Bill James
A: 

It updates the property values on the person object using the supplied request parameters. This is called data binding and is documented here.

Daniel Rinser
+1  A: 

There is comprehensive documentation on the Grails web site

Behind the scenes, the properties on a Groovy/Grails object is a map of the domain class properties. The params object is also a map of the request parameters - basically the HttpServletRequest object CGI parameters. So the assignment will update the properties map with values from the params map, only where they match.

If you were to do this with straight Servlets & JSP's you would essentially be writing:

public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    Person person = new Person();
    person.firstName = request.getParameter('firstname');
    person.lastName =  request.getParameter('lastname');
    person.password = request.getParameter('password');
    ...
}

With Grails, you would essentially just write this in PersonController.groovy:

def save = {
     def person = new Person()
     person.properties = params
     ...
    }

So with Grails you don't need to worry too much about what the parameter names are since you should be using grails tags to output them and then the params mapping to get them back into the object. This lessens the stupid errors encountered when you mispel a parameter name.

You also can add more properties to the Person domain object and not have to write more getter/setter type statements.

MattS