数据绑定
应用场景:一个表单更新多个领域对象,在这个应用中,注册一个用户需要更新user和profile两个对象,我们新建一个register表单
grails-app\views\user\register.gsp
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Register New User</title> 5 <meta name="layout" content="main"/> 6 <style> 7 dd { 8 text-align: left; 9 margin-left: 80px; 10 margin-top: 5px; 11 } 12 </style> 13 </head> 14 15 <body> 16 <h1>Register New User</h1> 17 <g:hasErrors> 18 <div class="errors"> 19 <g:renderErrors bean="${user}" as="list" /> 20 </div> 21 </g:hasErrors> 22 <g:form action="register"> 23 <dl> 24 <dt>User Id</dt><dd><g:textField name="userId" value="${user?.userId}"/></dd> 25 <dt>Password</dt><dd><g:passwordField name="password" value="${user?.password}"/></dd> 26 <dt>Full Name</dt><dd><g:textField name="profile.fullName" value="${user?.profile?.fullName}"/></dd> 27 <dt>Bio</dt><dd><g:textArea name="profile.bio" value="${user?.profile?.bio}"/></dd> 28 <dt>Email</dt> 29 <dd> 30 <g:textField name="profile.email" value="${user?.profile?.email}"/> 31 <g:hasErrors bean="${user}" field="profile.email"> 32 <g:eachError bean="${user}" field="profile.email"> 33 <p style="color: red;"><g:message error="${it}"/></p> 34 </g:eachError> 35 </g:hasErrors> 36 </dd> 37 <dt><g:submitButton name="register" value="Register"/></dt> 38 </dl> 39 </g:form> 40 </body> 41 </html>
表单提交给register这个action,在UserController中新建一个actioon
grails-app\controllers\com\grailsinaction\UserController.groovy
1 def register = { 2 def user = new User(params) 3 if (user.validate()) { 4 user.save() 5 flash.message = "Successfully Created User" 6 redirect(uri: '/') 7 } else { 8 flash.message = "Error Registering User" 9 return [ user: user ] 10 } 11 }