grailsgroovygsp

Groovy server page, creating a table


I have a situation where my domain has two fields such as

Class test{
   static constraints {
     testno(nullable:true)
     opt(nullable:false, blank:false)
   }

   Double testno
   String opt
}

The opt has option values such as 'test', 'try', and 'final'.

Now I need to create a table in .gsp file using the above info such that

----------------------------------
         Test        Try       Final
-------------------------------------
TestNo   
-------------------------------------

The value for each opt is display as testNo in the row below.

I am not sure how to start here. I tried creating a table such that:

```<%
def column=[
['field':'Test'],
['field': 'Try'],
['field':'Final']
]
%>```

However, how do I add row in the table? In addition, how can I use the table in a different gsp table given that

class Result(){ test(nullable:true) hasMany=[test:Test]}

I would like it to render the table.gsp in result.gsp


Solution

  • You need to send all your tests to the view in your controller:

    def showTests() {
        // your controller code
        [tests: Test.findAll()]
    }
    

    Then, render the data using gsp tags in your view file (e.g. showTests.gsp):

    <html>
       <body>
         <table>
         <tr>
           <th></th>
           <th>Test</th>
           <th>Try</th>
           <th>Final</th>
         </tr>
        
         <g:each in="${tests}" var="t">
          <tr>
            <td>${t.testno}</td>
            <td>${t.opt == "test" ? "x" : ""}</td>
            <td>${t.opt == "try" ? "x" : ""}</td>
            <td>${t.opt == "final" ? "x" : ""}</td>
          </tr>
         </g:each>
        </table>
    
       </body>
    </html>
    

    This is just a very simple solution to your problem.

    Using it as a subresource

    If your Tests are contained in another resource like Result, you can access them in two ways.

    If you send your entire report to your view you can use:

    // controller
    def showResult() {
        // your controller code
        [result: Result.get(/*id...*/)]
    }
    
    // showResult.gsp view, just change this line
    <g:each in="${result.tests}" var="t">
    

    Otherwise, if you want to send only tests to your existing view from the main example above:

    // controller
    def showTests() {
        // your controller code
        def result = Result.get(/*your id*/)
        [tests: result.tests]
    }