grails domain without saving it
I have :
def userList = [];
if(!User.findAllByGrade(10)){
userList.add(new User());
}else{ ..... }
<g:each in="${userList}" var="user">
<!-- my big form -->
</g:each>
I need to display a form whether the user exists or not ... so I just add "dummy" user to开发者_如何学编程 the list. But it will produce errors:
Message: object references an unsaved transient instance - save the transient instance before flushing: User Caused by: object references an unsaved transient instance - save the transient instance before flushing: User
I could use to copy the forms, but I just wonder how to solve this ...
How about the if-else taglib:
<g:if test="${userList}">
<!-- Your form for no-user case here. -->
</g:if>
<g:else>
<!-- Your form for g:each case here. -->
</g:else>
A bit dirty, but it should work:
def userList = [];
if(!User.findAllByGrade(10)){
userList.add([:]);
}else{ ..... }
So instead of creating a new User instance, just add an empty hashtable to the list; if the result doesn't look ok, you need to do a bit more work:
def userList = [];
if(!User.findAllByGrade(10)){
userList.add([name:"", age:"", foobar:""]);
}else{ ..... }
I.e. create entries in the hashtable that correspond to the attributes of User
.
How about adding null
to the list instead of new User()
and then, in gsp, referring to user's properties using safe navigation operator .?
(like user?.name
so NPE wouldn't be thrown)
So the code will be more like:
def userList = [];
if(!User.findAllByGrade(10)){
userList. << null
}else{ ..... }
<g:each in="${userList}" var="user">
<!-- my big form -->
<g:textField name="name" value="${user?.name}" />
</g:each>
精彩评论