[英]Grails - Make Embedded Field in Domain Class Nullable
如何將嵌入字段指定為可空? 在下面的簡單示例中,如果沒有與項目關聯的價格,我希望字段價格可以為空。 但是,如果有價格,則需要貨幣中的兩個字段。 以下代碼不起作用。 當我嘗試保存該項時,它會抱怨貨幣字段的空值。
class Item {
static constraints = {
price(nullable:true)
}
static embedded = ['price']
Currency price
}
class Currency {
Integer quantity
String currencyType
}
只需在嵌入對象中定義static constraints
。
class Currency {
...
static constraints = {
quantity(nullable:true)
currencyType(nullable:true,validator:{ String val, Currency obj ->
if ((val && !obj.quantity) || (!val && obj.quantity)) {
return 'Currency.both.fields.required';
}
})
}
}
然后,只需將'Currency.both.fields.required'
添加到messages.properties
即可顯示相應的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.