Monday, May 31, 2010

in-line editing in scaffolded show.gsp

In the default pages created by the scaffolding mechanism of grails, it is quite cumbersome that whenever you want to change a value of a domain class you have to go to the edit page and afterwards back to the show page. Two complete site loads that do not fit into the web 2.0 paradigm.

Usually one would apply in-line editing to bring in a cool and useful AJAX feature and in fact every JS library seems to have built-in support. It is however quite labourous if you have to add this feature manually to every field even if you make things easier with a tag lib as suggested in the book "Beginning Groovy and Grails" by Christopher M. Judd, Joseph Faisal Nusairat and James Shingler.

I thought about the problem and then decided to try to combine scaffolding with this technique. I used the example from the book as a guideline.

I changed the following entry within show.gsp:

<td valign="top" class="value">\${fieldValue(bean: ${propertyName}, field: "${p.name}")}</td>

to:
<td>
 <g:editInPlace 
  id="${p.name}"       
  url="[action: 'editField', id:${propertyName}.id]"
  rows="1"
  cols="10"
  paramName="${p.name}">\${fieldValue(bean: ${propertyName}, field: "${p.name}")}
 </g:editInPlace>
</td>

One can use the TagLib given by the book, but you have to modify the action in order to work with arbitrary fields. Add the following method to the scaffolded Controller.groovy (/src/templates/scaffolding):

def editField = {
  // Retrieve member
  def ${propertyName} = ${className}.get(params.id)
  if(${propertyName})
      {
      ${propertyName}.properties = params
      ${propertyName}.save()
      // Render a new page.
      render params.get(params.editorId)
  }
    }

No comments:

Post a Comment