Search code examples
grailsgsp

How to show results in a list Grails gsp


I have the Student class that has a relationship one-to-many with the Note class

class Student {
   String name
   static hasMany = [notes: Note]
}

class Note {
    double note
    int bimester
    static belongsTo = [student:Student]
}

When I display the result to the user in my userNotes.gsp It is shown: I use: <g:each var="n" in="${studentInstance.notes}">

Discipline    Note  Bimester
mathematics | 0    |   1
mathematics | 0    |   2
mathematics | 0    |   3
mathematics | 0    |   4
portuguese  | 0    |   1
portuguese  | 0    |   2
portuguese  | 0    |   3
portuguese  | 0    |   4

But I wanted to show the following:

Discipline | Bimester 1 | Bimester 2 | Bimester 3 | Bimester 4
mathematics      0            0            0            0
portuguese       0            0            0            0

Solution

  • You can group the data in the controller:

    def userNotes() {
       def student = Student.get(1)
       def disciplines = [:].withDefault { [0, 0, 0, 0] }
       for (Note note in student.notes.sort { it.bimester }) {
           disciplines[note.discipline].set(note.bimester - 1, note.note)
       }
       [disciplines: disciplines]
    }
    

    and display it with

    <table>
        <thead>
            <tr>
                <th>Discipline</th>
                <th>Bimester 1</th>
                <th>Bimester 2</th>
                <th>Bimester 3</th>
                <th>Bimester 4</th>
            </tr>
        </thead>
        <tbody>
        <g:each in="${disciplines}" var="entry">
            <tr>
                <td>${entry.key}</td>
                <g:each in="${entry.value}" var='bimester'>
                <td>${bimester}</td>
                </g:each>
            </tr>
        </g:each>
        </tbody>
    </table>