Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails Scaffolding with friendly labels (instead of ID keys) for foreign-key associations

Tags:

grails

groovy

I trying to use Grails Scaffolding to throw a quick CRUD application together around some legacy database tables (see this previous StackOverflow question for the saga thus far). I am now past the worst of the issues, and have a functioning CRUD app, but there is one problem remaining with general usability.

Many of my domain objects have foreign-key associations with other domain objects. A Contact belongs to an Owner, etc.

However, on the CRUD pages for Contact, I don't want to see the actual id key for Owner... because that doesn't mean anything to human users. I want the more human-friendly Owner.name value displayed on the screen instead.

The "list" and "show" Views explicitly deal with all attributes in the View's automatically-generated code, and I have the ability to tweak that code to control what's presented. However, the "create" and "edit" Views do not list out all the attributes. Instead those Views make some kind of Grails taglib call like this:

...
<fieldset class="form">
    <g:render template="form"/>
</fieldset>
...

This call apparently auto-detects at runtime what the fields are, and makes its own decisions about how to display them. For domain objects having associations, it makes the bad decision of displaying the associated object's gibberish ID rather than a more human-friendly attribute.

Is there an "easy" (or at least "best practice") way for changing the way that fields are displayed on an "edit" or "create" view? Surely this is a common issue whenever using Scaffolding is used with domain objects having associations.

like image 493
Steve Perkins Avatar asked Feb 10 '12 16:02

Steve Perkins


1 Answers

Oh, duh... you can just implement a "toString()" method on the associated domain object, having it return the field you want used for display purposes:

class Owner {

    String id  // not human-friendly
    String name  // human-friendly
    // ...etc...

    String toString() {
        return name
    }
}

Now when you're on a CRUD View for Contact, which has a field for its Owner association, what gets displayed on the screen is the Owner.name attribute rather than Owner.id or some ugly object reference.

like image 113
Steve Perkins Avatar answered Sep 25 '22 01:09

Steve Perkins