是否可以一次添加/更新多個實例?例如,我們有一個帶有bname,tile的域類書。在gsp中,我們正在顯示一個包含多個bname和標題文件的表單。任何人都可以讓我知道如何編寫crteate /編輯操作?在grails中多創建/編輯
1
A
回答
0
這是可能的。您需要創建bulkCreate/bulkUpdate頁面,並附上適當的控制器和服務方法。沒有什麼可以阻止你在服務中執行類似如下的操作:
def book1 = new Book(bname1, btitle1)
def book2 = new Book(bname2, btitle2)
book1.save()
book2.save()
你可能想在那裏進行驗證。 bname1等是您在表單中定義的參數。
0
使用上述代碼在一個循環,並能(在0..booksSize I)添加/更新記錄成功
爲{ 高清BOOK1 =新的圖書(bname1,btitle1) 如果(!BOOK1 .save()){ flash.message =「錯誤消息」 }}
如果有與錯誤/無效數據如何顯示隨着CONT/GSP錯誤輸入的數據用戶的任何行?從上面我只得到最後一行錯誤。
0
我知道這是幾歲,但我想我會爲這個常見問題添加一個更新的答案。
Grails提供了一些方便的工具來允許使用Command Objects,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$/)
}
}
實質上是創建兩個命令對象。一個用於表單數據的單個實例,另一個用於單個實例的列表。 list命令對象使用ListUtils和FactoryUtils來處理「批量」表單輸入,並且每個單個實例仍然通過約束進行驗證。
您需要從Apache公地集合導入ListUtils和FactoryUtils:
import org.apache.commons.collections.FactoryUtils
import org.apache.commons.collections.ListUtils
這將在行動中使用這樣的:
def save(ShiftEntryListCommand cmd) {
//other action code follows ...
}
現在所有散裝形式的數據來保存方法是由命令對象處理和驗證。要保存記錄,您可以遍歷列表並在每個記錄上調用save()
,或者使用Hybernate方法進行批量插入。在我們的案例中,我們選擇循環播放每條記錄。不知道爲什麼。
希望有人認爲這有用。
Thanks hvgotcodes – Honey 2010-11-18 04:05:33