How to save multiple object from one view using Grails

為{幸葍}努か 提交于 2020-01-14 06:05:09

问题


This question is in follow up to this post Grails one to many relationship view

The example suggested there is not working and throwing following exception at run time

null id in blog.omarello.Phone entry (don't flush the Session after an exception occurs). Stacktrace follows:
Message: null id in blog.omarello.Phone entry (don't flush the Session after an exception occurs)
   Line | Method
->>  43 | doCall  in blog.omarello.ContactController$_closure4$$ENLORkU6
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   886 | runTask in java.util.concurrent.ThreadPoolExecutor$Worker
|   908 | run . . in     ''
^   662 | run     in java.lang.Thread

I think rather then making the example work can any one help me understand how can I create a GSP which can let me save multiple instances of same domain class. For example, a GSP which can let me insert multiple Book instances at once?


回答1:


Change the Contact class in the phone example as follows and it should work fine.

package blog.omarello

import org.apache.commons.collections.list.LazyList;
import org.apache.commons.collections.FactoryUtils;

class Contact {

    static constraints = {
        firstName(blank:false)
        lastName(blank:false)
    }

    String firstName
    String lastName
    String nickName


 List phones = LazyList.decorate(new ArrayList(),
                                  FactoryUtils.instantiateFactory(Phone.class));


//    List phones = new ArrayList()
    static hasMany = [ phones:Phone ]

    static mapping = {
        phones cascade:"all-delete-orphan"
    }

//    def getPhonesList() {
//        return LazyList.decorate(
//              phones,
//              FactoryUtils.instantiateFactory(Phone.class))
//    }

    def String toString() {
        return "${lastName}, ${firstName}"
    }
}



回答2:


Once again, examine the project I linked on github. It is a demonstration of some of the one of the better practices for doing this. Particularly, look at the question/index, as this is what the view can look like. The actual saving piece is done in the QuestionService, used by the QuestionController. This project does exactly what you're trying to do. Review it.



来源:https://stackoverflow.com/questions/8776212/how-to-save-multiple-object-from-one-view-using-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!