表单提交Grails中的多个Domain对象

时间:2011-06-07 07:25:53

标签: grails

我是Grails的新手。我正在学习基本的CRUD操作。这里我有2个域对象Person和Address。每个人只需要一个地址

所以我有一个gsp表单,它收集用户名,名字,姓氏,年龄和地址字段,并且应该存储在数据库Person和Address中的2个表中。那么如何编写映射2个域类(人员和地址)的控制器中的代码。

感谢您的回答。

更新:我使用了以下不起作用的代码

package com.deltaintech.wr

class Person {
    String username
    String password
    String firstname
    String lastname
    String email
    Address address

    static constraints = {
    }
}


package com.deltaintech.wr

class Address {

    String address1
    String address2
    String city
    String state
    String country
    String zipcode

    static constraints = {
    }
}

package com.deltaintech.wr.register
import com.deltaintech.wr.*

class RegisterController {

    def index = { 

    }

    def register = {

        Person person = new Person(params)
        person.save()

    }
}

<!--
  To change this template, choose Tools | Templates
  and open the template in the editor.
-->

<%@ page contentType="text/html;charset=UTF-8" %>

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Sample title</title>
  </head>
  <body>
    <h1>Sample line</h1>
  <g:form action="register">
   User Name <g:textField name="username"/><br>
   Password <g:passwordField name="password" /><br>
   First Name <g:textField name="firstname"/><br>
   Last Name <g:textField name="lastname"/><br>
   Email <g:textField name="email" /><br>
   Address1 <g:textField name="address.address1"/><br>
   Address2 <g:textField name="address.address2" /><br>
   City <g:textField name="address.city" /><br>
    State<g:textField name="address.state" /><br>
    Country <g:textField name="address.country" /><br>
   Zip Code <g:textField name="address.zipcode" /><br>
    <g:submitButton name="create" value="Create"/>
  </g:form>
</body>
</html>


Error 500: Executing action [register] of controller [com.deltaintech.wr.register.RegisterController] caused exception: not-null property references a null or transient value: com.deltaintech.wr.Person.address; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: com.deltaintech.wr.Person.address
Servlet: grails
URI: /system/grails/register/register.dispatch
Exception Message: not-null property references a null or transient value: com.deltaintech.wr.Person.address 
Caused by: not-null property references a null or transient value: com.deltaintech.wr.Person.address 
Class: RegisterController 
At Line: [13] 

1 个答案:

答案 0 :(得分:2)

class Person { 
    String name 
    Address address 
} 

class Address { 
   String city 
} 
差距必须看起来像:

<g:form action="save">
    <g:textField name="name"/>
    <g:textField name="address.city"/>
</g:form>

在控制器中:

def p = new Person(params)
p.save()