2014-03-30 33 views
1

我想在控制器的保存操作期間修改或添加域屬性。我正在使用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?

+1

您的代碼應該可以工作。您在開發過程中是否使用GGTS或其他IDE?你可以調試,以確保'User.findById'返回你所期望的。通常我傾向於使用'springSecurityService.currentUser' –

+0

我在爲stockInstance.stockBy','springSecurityService.getPrincipal()。id'和'User.findById(springSecurityService.getPrincipal()。id)分配stockBy之後做了println。 '我得到了所有正確的結果。問題是,這個結果在驗證時沒有被保存到域中,所以我得到'stockBy'不能爲空的錯誤。 –

+0

發佈您的域名代碼,您是否使用驗證器? –

回答

1

我一直在努力解決同樣的問題。問題是域對象會記住以前的錯誤,需要在將用戶添加到stockInstance.stockBy後重新驗證:

stockInstance.stockBy = springSecurityService.currentUser 
    stockInstance.validate() 
+0

聽起來不錯。原始代碼與已驗證失敗的實例一起工作,因爲Grails會在將命令傳遞給操作之前驗證命令對象。此時該對象無效,因此存在錯誤。代碼然後改變對象的狀態,然後調用.hasErrors()。 hasErrors()將返回true(並且應該),直到對象的錯誤被清除和/或被重新驗證。 –