Search code examples
grailsgsp

How can I sort hasMany associations in scaffolded GSPs in Grails 3.1.8


I have a domain object, Question, with a hasMany relationship to another domain class, Option, which implements Comparable<Option>. I would like the options to be sorted in the GSP. Is there an easy way to do this, or do I need to generate the views and edit them manually?


Solution

  • This turned out to be relatively easy, however finding the answer was a real pain because the documentation for the Grails Field Plugin is lacking detail.

    Just add a GSP called grails-app/views/[domain-class]/[action]/[property]/_displayWidget.gsp.

    The contents of that file is a template that handles the sorting and displaying...

    grails-app/views/question/show/options/_displayWidget.gsp

    <ul>
        <g:each in="${value?.sort()}" var="val">
            <li><g:link controller="${val.class}" action="show" id="${val.id}">${val}</g:link></li>
        </g:each>
    </ul>