Command Objects « Intelligrape Groovy & Grails Blogs
Subscribe via E-Mail:

Command Objects

Posted by imran

What is a command object ?

Command object is a non persistent class used for data-validation. The main advantage of using the Command objects is that we can validate those forms that do not map to the domain class.

Where to define command object ?

You can define command classes in the grails-app/controllers directory or even in the same file as a controller; or you may also define it in grails-app/src/groovy.

How to define command object ?

In one of my recent  projects I did it like this :

public class RegisterUserCommand {
 
    String username
    String password
    String firstName
    String lastName
    String email
    String age
 
        static constraints={
        username blank:false,size:30
        password blank:false
        cardNo creditCard:true
        firstName matches/[A-Za-z ]/
        lastName matches /[A-Aa-z ]/
        email blank:false,email:true
        age range:18..60
    }
 
}

How to define custom validators ?

Lets us assume we ‘ve one more field as verifyPassword and we want to match it to the password field. We ‘ll use custom validator as :

verifyPassword blank:false,validator:{val,obj ->
        if(!(val==obj.password))
        return ['field.match.message','Cofirm Password ','Password']
}

Note :Here we ‘ve returned our own customized message instead of the default error message, along with the parameters.The default error message is implicitly returned when we use default validations.

How to use our command object now ?

When a request comes in, Grails will automatically create a new instance of the command object, bind the incoming request parameters to the properties of the instance, and pass it to you as the argument.
Thus,you can create or modify your controller action as :

def registerUser = { RegisterUserCommand cmd ->
    if(!cmd.hasErrors()) {
        // your code does something
    }
    else{
            // your code does something
    }
}
 
}

How do I display error messages on my gsp page ?

To do so you first need to pass the command object to your gsp page as :

     render (view:'myErrorPage', model:[myCmd:cmd])

Then in the myErrorPage.gsp you can use g:renderErrors tag to display the errors(if any). But before displaying errors u need to make sure there are errors by making use of g:hasErrors tag :

<g:hasErrors bean="${myCmd?.errors}">
          <div class="errors">
            <g:renderErrors bean="${cmd}"/>
          </div>
   </g:hasErrors>

But it shows default error messages.How can I define my own error messages ?

To do so you need to modify the /grails-app/i18n/message.properties_ file by creating your own messages or replacing the default messages by custom messages :

field.blank.message={0} cannot be blank             #my message for blank fields
fields.does.not.match.message={3} and {4} do not match           # my verifyPassword error message
field.number.notallowed.message={3} must have alphabets only           # u can guess this

I can’t follow the parameterized messages..can u please ellaborate.

The error message  is defined as:

default.doesnt.match.message=Property [{0}] of class [{1}] with value [{2}] does not match the required pattern [{3}]

[{0}] = property
[{1}] = class
[{2}] = value
[{3}] = constraint

The above example is a default message provided in the message.properties file.One can easily modify the message to suit to the requirement.
Or you choose to define your own message.eg., for the example given in the begining , the error message for the verifyPassword validator can be defined as :

fields.does.not.match.message={3} and {4} does not match

So in the validator the parameters and the message are returned as :

return ['field.match.message','Cofirm Password ','Password']

Hope you find this useful.
Imran Mir
imran@intelligrape.com

  • Share/Bookmark
This entry was posted on Tuesday, May 26th, 2009 at 10:04 am and is filed under Grails . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Responses to “Command Objects”

  1. [...] mentioned the Command Object and treating the interaction with the data store as different from the interaction with the web. We [...]

  2. Daxon says:

    This is amazing!
    Great post

  3. Houria says:

    Thanks for sharing, see you then. Are there any forums that you recommend I join ?

Leave a Reply