2012-03-21 126 views
2

我做了一些表單驗證在我的控制器(使用插件),並設置所謂status =true/false如果驗證通過布爾變量/失敗返回回同一頁面,如果驗證Grails的失敗

此驗證update發生行動,並且請求來自edit.gsp。 如果驗證失敗,我希望控件返回到edit.gsp。我可以做到這一點,或者我必須單獨創建update.gsp,並複製edit.gsp的內容,以便在update.gsp頁面上顯示帶有錯誤消息的已編輯表單值?我希望避免將所有其他參數傳遞給後端,並僅支持1字段的消毒檢查。
它應該看起來類似於JavaScript,但實際上後端驗證重定向到錯誤相同的頁面。 我該如何實現這一目標? 成功驗證後,我正在重定向到manageTemplate.gsp

問候, 在此先感謝

+0

那麼,你是怎麼走的? – David 2012-03-27 11:15:11

回答

3

根據您使用插件,我覺得最簡單的方法是寫你的域對象的自定義驗證是如何引發的驗證。更多信息:http://grails.org/doc/latest/ref/Constraints/validator.html

如果你不想(或不能)沿着這條路線走下去,你可以手動檢查控制器插件的驗證。它基本上與腳手架Grails頁面/控制器使用的模式相同。

在您的控制器中,您可以使用您的插件進行驗證,如果該域實例未驗證,您將用戶重定向回編輯操作幷包含'params'。這樣所有的領域仍然像以前一樣充滿。

從腳手架的Grails控制器(對於域對象調用代碼)中的更新片段:

// ... 
    // Code above here just gets the domain object to edit (tagInstance in this case) 
    // and checks that the object hasn't be updated in the meantime 

    tagInstance.properties = params 

    // params have been applied to object, you can now do custom validation 

    def status = extraValidationService.validate(tagInstance) // or however you run the validation 

    if (!status) { 
     flash.message = "Did not pass custom validation" 
     render(view: "edit", model: [tagInstance: tagInstance]) // Back to same edit page (field values maintained) 
     return   
    } 

    // Everything below here is unchanged 

    if (!tagInstance.save(flush: true, failOnError: false)) { 
     render(view: "edit", model: [tagInstance: tagInstance]) 
     return 
    } 

    flash.message = message(code: 'default.updated.message', args: [message(code: 'tag.label', default: 'Tag'), tagInstance.id]) 
    redirect(action: "show", id: tagInstance.id) // This is where you redirect to the manageTemplate action.gsp 

這會不會給你驗證失敗的領域審定突出。爲了得到你可以使用自定義驗證器方法,或者你可以(我從來沒有做過)能夠手動'告訴'一個域對象哪些字段驗證失敗,爲什麼。

相關問題