register
other register

Thursday, January 15, 2009

Command Object and Error Messages

"Grails command Objects provide a simple mechanism to validate from fields that do not map directly to domain objects. "

Command Object

class JetCommand {
  String number
  String name
 
  static constraints = {
    number(blank: false, nullable: false, matches: "\\d+")
    name(nullable: false)
  }
}

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.

If a custom error message is preferred, then look at the corresponding error code for the above constraints. Add custom error messages in the grails-app/i18n/messages.properties file:

jetCommand.number.blank=The number can't be blank
jetCommand.number.matches.invalid=The number can only be digital numbers
jetCommand.name.nullable=The name can't be null


Controller:

class JetController {
  def jet = { JetCommand cmd ->
  if (cmd.hasErrors()) {
    cmd.errors.allErrors.each {
    println it
  }
}

// You don't have to do the following code, because the Grails will handle it for you.
// If you do the following code, there will be duplicate error messages 

/**
if (cmd.errors.hasFieldErrors("name")) { 
cmd.errors.rejectValue('choice', 'searchCommand.name.nullable') 
}
         if (cmd.errors.hasFieldErrors("number")) {
                 if (cmd.errors.getFieldValue("number").isEmpty()) {
                     cmd.errors.rejectValue('number', 'searchCommand.number.blank')
                 }
                 else {
                     cmd.errors.rejectValue('number', 'searchCommand.number.matches.invalid')
                 }
             }
**/
render (view: 'admin', model:[jetCommand: cmd, key1: object1, key2: object2])
}
}
}


GSP page

You can display the error messages in the GSP page:


  


Customised Validator:

You can also add a customised validator:

static constraints = {
  number(validator: {
    if (it.isEmpty() || it == null || !(it ==~ /\d+/)) {
      return ['numberJet']  // numberJet is the error code
    }
  })
}

In this case, in the messages.properties, you should add a error message with the error code:

jetCommand.number.numberJet=Number field is not valid

No comments: