Monday, 18 February 2008

Grails: Tip for scaffolding required fields

Scaffolding is one of the most useful features of grails and customizing scaffolding it's basic for increase your productivity.

One thing I've customized is render a '*' for required fields, for this you have to install scaffolding templates with grails install-templates.

This is a fragment of the original templates/scaffolding/create.gsp,


props.each { p ->
if(p.type != Set.class) {
cp = domainClass.constrainedProperties[p.name]
display = (cp ? cp.display : true)
if(display) { %>
<tr class="prop">
<td valign="top" class="name">
<label for="${p.name}">${p.naturalName}:</label>
</td>
<td valign="top" class="value \${hasErrors(bean:${domainClass.propertyName},field:'${p.name}','errors')}">
${renderEditor(p)}
</td>
</tr>
<% } } } %>


I'm going to introduce a line, to check if the field has a constraint blank:false, and in this case render as a required field.

if(!cp?.blank) { %><span class="req">*</span><% } %>

The updated version complete:
   props.each { p ->
if(p.type != Set.class) {
cp = domainClass.constrainedProperties[p.name]
display = (cp ? cp.display : true)
if(display) { %>
<tr class="prop">
<td valign="top" class="name">
<% if(!cp?.blank) { %><span class="req">*</span><% } %>
<label for="${p.name}">${p.naturalName}:</label>
</td>
<td valign="top" class="value \${hasErrors(bean:${domainClass.propertyName},field:'${p.name}','errors')}">
${renderEditor(p)}
</td>
</tr>
<% } } } %>

That's all folks.

1 comments:

Anonymous said...

doubt your code will pass the turkey test!