views:

381

answers:

3

Hi,

When using Grails, the GSP code to render each form field looks something like this:

<tr class="prop">
  <td valign="top" class="name"><label for="username">Login Name:</label></td>
  <td valign="top" class="value ${hasErrors(bean: person, field: 'username', 'errors')}">
    <input type="text" id="username" name="username" value="${person.username?.encodeAsHTML()}"/>
  </td>
</tr>

<tr class="prop">
  <td valign="top" class="name"><label for="userRealName">Full Name:</label></td>
  <td valign="top" class="value ${hasErrors(bean: person, field: 'userRealName', 'errors')}">
    <input type="text" id="userRealName" name="userRealName" value="${person.userRealName?.encodeAsHTML()}"/>
  </td>
</tr>

<tr class="prop">
  <td valign="top" class="name"><label for="passwd">Password:</label></td>
  <td valign="top" class="value ${hasErrors(bean: person, field: 'passwd', 'errors')}">
    <input type="password" id="passwd" name="passwd" value="${person.passwd?.encodeAsHTML()}"/>
  </td>
</tr>

Notice that almost exactly the same 5 lines of GSP/HTML code is repeated for each form field. This doesn't seem very DRY to me, and I'm wondering if others have found a better approach?

I've found 2 plugins which attempt to address this problem, the form helper and bean-fields. If anyone has experience using either of these, I'd be very interested to hear from them. Alternatively, if there are other solutions/plugins, please let me know.

Thanks. Don

+1  A: 

I work in Rails not Grails, but it seems that you can also use partials in Grails. See this link. According to this doc:

Partial templates are officially called templates in the Grails documentation.

This is from 2008 so I hope (and guess) it still works.

Yar
Templates are definitely still used by Grails. I guess I could create a template that generates the content within each `<tr>...</tr>`
Don
We also have helpers in Rails, but it depends: if it contains markup, GENERALLY, we do it with partials. Partials -- and I'd imagine that templates in grails, too -- allow you to pass local variables and can also access instance variables. So basically we do code DRYing using helpers and template drying using partials. Although this question has peaked my curiosity as to what I'm missing in Rails, too :) Thanks!
Yar
+3  A: 

Using the bean-field plugin. Your code will become:

<bean:withBean beanName="person">
    <bean:field property="username" label="Login Name:"/>
    <bean:field property="userRealName" label="Full Name:"/>
    <bean:field property="passwd" label="Password:"/>
</bean:withBean>

Can you find a DRYer solution?

fabien7474
+4  A: 

Yes, bean-fields plugin is very DRY… your 20 lines can be replaced with one line:

<bean:form beanName="person" properties="username, userRealName, passwd”/>

(Assuming you have i18n properties set)

k s