grailsgroovygsp

How do I render a field in the gsp page from another domain?


Here is my scenario:

Class Domain1 {
  static hasMany=[ tests : Domain2 ]
  static constraints = { tests(nullable: true) }
}

And

Class Domain2 {
  Double t1, String t2
  static constraints={
    t1(nullable:true
    t2(nullable:false,blank:false)
  }
}

I need to display t1 from domain2 in domain1 with the ability to edit.


Solution

  • I need to display t1 from domain2 in domain1 with the ability to edit.

    See the project at https://github.com/jeffbrown/samdomain.

    grails-app/domain/samdomain/Domain1.groovy:

    package samdomain
    
    class Domain1 {
        static hasMany = [tests: Domain2]
    }
    

    grails-app/domain/samdomain/Domain2.groovy:

    package samdomain
    
    class Domain2 {
        Double t1
        String t2
    
        static constraints = {
            t1 nullable: true
        }
    }
    

    grails-app/controllers/samdomain/DemoController.groovy:

    package samdomain
    
    class DemoController {
    
        def index() {
            def d1 = new Domain1()
            d1.addToTests t1: 42, t2: 'Fourty Two'
            d1.addToTests t1: 2112, t2: 'Twenty One Twelve'
    
            [domainInstance: d1]
        }
    
        def update() {
            render "Updated values: ${params.t1Values}"
        }
    }
    

    grails-app/views/demo/index.gsp:

    <%@ page contentType="text/html;charset=UTF-8" %>
    <html>
    <head>
        <meta name="layout" content="main"/>
        <title>Simple Demo</title>
    </head>
    
    <body>
    
    <g:form action="update" method="POST">
        <table>
        <g:each var="d2" in="${domainInstance.tests}">
            <tr>
                <td>${d2.t2}</td>
                <td><g:textField name="t1Values" value="${d2.t1}"/></td>
            </tr>
        </g:each>
        </table>
        <g:submitButton name="Update"/>
    </g:form>
    </body>
    </html>