1

I'm a newbie on grails. I am now currently working on my scaffolding templates especially on my controllers. I wanted a customized controller everytime I generate it so I used "install-templates". I always create a Command object on controllers, is it possible to include the fields from my domain class to my command object in my generated controller? I know I have to do it in controller templates but i dont know how to code it or if it is even possible. So everytime I use generate-controllers, the fields on the Command Object is already set.

${className}Command implements java.io.Serializable{

    constraints = {}

} 

and for example my Domain class looks like this:

class Person{

String name
int age
double height
}    

I want it to automatically generate the fields of my domain class in the Command object on my generated controller through editing the controller template. is it possible? thanks for sharing your knowledge.

antibry
  • 282
  • 5
  • 22

2 Answers2

2

edit.gsp, show.gsp and list.gsp templates all have logic for creating fields basing on domain class, you can see there how it's done.

Basically, when you include groovy code in your template, you can access domain class by using domainClass variable, and then you can print properties declarations by iterating over array returned by getProperties(), like this:

<%
    domainClass.properties.each {
        println "    ${it.type} ${it.name}"
    }
%>
socha23
  • 10,171
  • 2
  • 28
  • 25
  • thanks! this one works, I modified it a bit to get the result I really wanted.by using your code the output id this: class java.lang.String name so what I did is change the ${it.type} into ${it.type.simpleName}. thanks for the additional knowledge! :-) – antibry Mar 27 '12 at 01:37
1

Interesting question - why do you think you need the command object? This way, you are violating the dry principle.

As you are just starting with grails, you should just try to use grails as it is inteded to be used and not try to enhance it.

As soon as you've created your first fully featured grails project, you'll see the beauty of the grails design - without the need of implicit command objects :-) - or chose another framework

rdmueller
  • 10,742
  • 10
  • 69
  • 126
  • +1 for @Ralf suggestion. Commands are supposed to help with validation of constraints which span several domain objects or are done on fields outside of the domain object (like repeated password validation, etc.) to allow keeping the domain clean... By generating command objects for each controller/domain object you will end up with a lot of repeated code that will soon become out of sync with your model anyway (or you will be adding fields twice - once in the model and once in your commands). – Marcin Niebudek Mar 27 '12 at 08:29