Command Objects

Grails Command Objects provide a simple mechanism to validate form fields that do not map directly to domain objects. Using the validation constraints concept that applies to domain classes, including the validate() method and "errors" dynamic property, Grails applies the concept of command objects to controller actions.

Controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create, populate and validate. Before the controller action is executed Grails will create an instance of the command object class, populate the properties of the command object with request parameters having corresponding names and the command object will be validated.

class LoginController {
  def login = { LoginCommand cmd ->
         if(cmd.hasErrors()) {
                redirect(action:'loginForm')
         }
         else {
            // do something else
        }
  }
}
The command object class may be defined under src/groovy/ or under grails-app/controllers/. The command object class may also be defined in the same source file as the controller that uses it.
class LoginCommand {
   String username
   String password
   static constraints = {
           username(blank:false, minSize:6)
           password(blank:false, minSize:6)
   }
}
The dynamic {{errors}} property on command objects is an instance of the Spring org.springframework.validation.Errors interface.

If you want to test what action the command object is being called for, you can use the RequestContextHolder:

import org.springframework.web.context.request.RequestContextHolder as RCH

static constraints = { username(nullable:false, blank:false, size: 3..25, validator: {val, obj-> //username must be unique - only for create function, not update def actionName = RCH.currentRequestAttributes().actionName if(actionName == "save" && (JsecUser.findByUsername(obj.username) != null)){ return "username.invalid.unique" } }) }

No Comments Yet

Post a Comment