我想在控制器的保存操作期間修改或添加域屬性。我正在使用grails 2.3.2,我的代碼如下:保存在grails中更改域的屬性2.3
@Transactional
def save(Stock stockInstance) {
if (stockInstance == null) {
notFound()
return
}
stockInstance.stockBy = User.findById(springSecurityService.getPrincipal().id)
if (stockInstance.hasErrors()) {
respond stockInstance.errors, view: 'create'
return
}
stockInstance.save flush: true
request.withFormat {
form {
flash.message = message(code: 'default.created.message', args: [message(code: 'stockInstance.label', default: 'Stock'), stockInstance.id])
redirect stockInstance
}
'*' { respond stockInstance, [status: CREATED] }
}
}
問題是,'stockBy'屬性正在生成null。 springsecurityservice正在返回一個值,但它沒有在propertyBy中設置。這段代碼在老版本的grails中運行良好。爲什麼這不適用於Grails 2.3.2?
您的代碼應該可以工作。您在開發過程中是否使用GGTS或其他IDE?你可以調試,以確保'User.findById'返回你所期望的。通常我傾向於使用'springSecurityService.currentUser' –
我在爲stockInstance.stockBy','springSecurityService.getPrincipal()。id'和'User.findById(springSecurityService.getPrincipal()。id)分配stockBy之後做了println。 '我得到了所有正確的結果。問題是,這個結果在驗證時沒有被保存到域中,所以我得到'stockBy'不能爲空的錯誤。 –
發佈您的域名代碼,您是否使用驗證器? –