{"id":49,"date":"2009-05-26T10:04:48","date_gmt":"2009-05-26T04:34:48","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=49"},"modified":"2010-06-09T15:52:38","modified_gmt":"2010-06-09T10:22:38","slug":"command-objects","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/command-objects\/","title":{"rendered":"Command Objects"},"content":{"rendered":"<p><strong>What is a command object ?<br \/>\n<\/strong><br \/>\n 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.<\/p>\n<p><strong>Where to define command object ?<\/strong><\/p>\n<p>You can define command classes in the <em>grails-app\/controllers<\/em> directory or even in the same file as a controller; or you may also define it in <em>grails-app\/src\/groovy.<\/em><\/p>\n<p><strong> How to define command object ?<br \/>\n<\/strong><br \/>\nIn one of my recent\u00a0 projects I did it like this :<\/p>\n<pre lang=\"groovy\">public class RegisterUserCommand {\r\n\r\n    String username\r\n    String password\r\n    String firstName\r\n    String lastName\r\n    String email\r\n    String age\r\n\r\n        static constraints={\r\n        username blank:false,size:30\r\n        password blank:false\r\n        cardNo creditCard:true\r\n        firstName matches\/[A-Za-z ]\/\r\n        lastName matches \/[A-Aa-z ]\/\r\n        email blank:false,email:true\r\n        age range:18..60\r\n    }\r\n\r\n}<\/pre>\n<p><strong>How to define custom validators ?<\/strong><\/p>\n<p>Lets us assume we &#8216;ve one more field as<em> verifyPassword <\/em>and we want to match it to the password field. We &#8216;ll use custom validator as :<\/p>\n<pre lang=\"groovy\">verifyPassword blank:false,validator:{val,obj ->\r\n        if(!(val==obj.password))\r\n        return ['field.match.message','Cofirm Password ','Password']\r\n}<\/pre>\n<p>Note :Here we &#8216;ve returned our own customized message instead of the default error message, along with the parameters.The <em>default error message<\/em> is implicitly returned when we use default validations.<\/p>\n<p><strong>How to use our command object now ?<\/strong><\/p>\n<p>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.<br \/>\nThus,you can create or modify your controller action as :<\/p>\n<pre lang=\"groovy\">def registerUser = { RegisterUserCommand cmd ->\r\n    if(!cmd.hasErrors()) {\r\n        \/\/ your code does something\r\n    }\r\n    else{\r\n            \/\/ your code does something\r\n    }\r\n}\r\n\r\n}<\/pre>\n<p><strong>How do I display error messages on my gsp page ?<br \/>\n<\/strong><br \/>\nTo do so you first need to pass the command object to your gsp page as :<\/p>\n<pre lang=\"groovy\">     render (view:'myErrorPage', model:[myCmd:cmd])<\/pre>\n<p> Then in the <em> myErrorPage.gsp <\/em>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 :<\/p>\n<pre lang=\"groovy\">\r\n<g:hasErrors bean=\"${myCmd?.errors}\">\r\n          <div class=\"errors\">\r\n            <g:renderErrors bean=\"${cmd}\"\/>\r\n          <\/div>\r\n   <\/g:hasErrors>\r\n<\/pre>\n<p><strong>But it shows default error messages.How can I define my own error messages ?<br \/>\n<\/strong><br \/>\nTo do so you need to modify the<em> \/grails-app\/i18n\/message.properties_<\/em> file by creating your own messages or replacing the default messages by custom messages :<\/p>\n<pre lang=\"groovy\">\r\nfield.blank.message={0} cannot be blank\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 #my message for blank fields\r\nfields.does.not.match.message={3} and {4} do not match\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 # my verifyPassword error message\r\nfield.number.notallowed.message={3} must have alphabets only\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 # u can guess this<\/pre>\n<p><strong>I can&#8217;t follow the parameterized messages..can u please ellaborate.<br \/>\n<\/strong><br \/>\nThe error message\u00a0 is defined as:<\/p>\n<pre lang=\"groovy\">default.doesnt.match.message=Property [{0}] of class [{1}] with value [{2}] does not match the required pattern [{3}]<\/pre>\n<p>[{0}] = property<br \/>\n[{1}] = class<br \/>\n[{2}] = value<br \/>\n[{3}] = constraint<\/p>\n<p>The above example is a default message provided in the message.properties  file.One can easily modify the message to suit to the requirement.<br \/>\n Or you choose to define your own message.eg., for the example given in the begining , the error message for the <em>verifyPassword<\/em> validator can be defined as :<\/p>\n<pre lang=\"groovy\">fields.does.not.match.message={3} and {4} does not match<\/pre>\n<p> So in the validator the parameters and the message are returned as :<\/p>\n<pre lang=\"groovy\">return ['field.match.message','Cofirm Password ','Password']<\/pre>\n<p>Hope you find this useful.<br \/>\nImran Mir<br \/>\nimran@intelligrape.com<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":9},"categories":[7],"tags":[103,107,104],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/49"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=49"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/49\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=49"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=49"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=49"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}