How to save multiple object from one view using Gr

2019-06-14 15:10发布

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?

2条回答
Animai°情兽
2楼-- · 2019-06-14 15:27

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}"
    }
}
查看更多
Explosion°爆炸
3楼-- · 2019-06-14 15:33

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.

查看更多
登录 后发表回答