grails中的多重创建/编辑

grails中的多重创建/编辑,grails,Grails,是否可以一次添加/更新多个实例?例如,我们有一个具有bname、tile的域类book。在gsp中,我们展示了一个包含多个bname和title文件的表单。有人能告诉我如何编写crteate/编辑操作吗?这是可能的。您需要创建bulkCreate/bulkUpdate页面,并附上适当的控制器和服务方法。没有任何东西可以阻止您在服务中执行以下操作: def book1 = new Book(bname1, btitle1) def book2 = new Book(bname2, btitle2)

是否可以一次添加/更新多个实例?例如,我们有一个具有bname、tile的域类book。在gsp中,我们展示了一个包含多个bname和title文件的表单。有人能告诉我如何编写crteate/编辑操作吗?

这是可能的。您需要创建bulkCreate/bulkUpdate页面,并附上适当的控制器和服务方法。没有任何东西可以阻止您在服务中执行以下操作:

def book1 = new Book(bname1, btitle1)
def book2 = new Book(bname2, btitle2)
book1.save()
book2.save()

你可能需要验证。bname1等是您在表单中定义的参数

在循环中使用了上述代码,并且能够成功地添加/更新记录

适用于(i为0..booksSize){ def book1=新书(b名称1,b标题1) 如果(!book1.save()){ flash.message=“错误消息” } }


如果有任何行包含错误/无效数据,如何在cont/gsp中显示用户输入的数据以及错误?从上面我只得到了最后一行错误。

我知道这已经有几年了,但我想我会为这个常见问题添加一个更新的答案

Grails提供了一些方便的工具,允许使用命令对象、ListUtils和FactoryUtils进行多记录更新

下面是一个可能用于保存多个时间卡轮班条目的示例:

class ShiftEntryListCommand {
    List<ShiftEntryCommand> entries = ListUtils.lazyList(
            new ArrayList(), FactoryUtils.instantiateFactory(ShiftEntryCommand)
    )
}

class ShiftEntryCommand {
    BigDecimal totalHours
    Date date
    String projectName

    static constraints = {
        totalHours (blank: false, min: 0.00, max: 24.00, matches: /^someRegex$/)
        date (blank: false, matches: /^someRegex$/)
        projectName (nullable: true, blank: true, matches: /^someRegex$/)
    }
}
它将用于这样的行动:

def save(ShiftEntryListCommand cmd) {
    //other action code follows ...
}
现在,save方法中的所有批量表单数据都由命令对象进行处理和验证。要保存记录,您可以在列表中循环并对每个记录调用
save()
,或者使用Hybernate方法进行批量插入。在我们的例子中,我们选择循环遍历每个记录。不知道为什么

希望有人觉得这个有用

def save(ShiftEntryListCommand cmd) {
    //other action code follows ...
}