Rendering command validation errors in redirection

I cannot display errors from my command object. This works well, but my .gsp view does not display the errors I raise.

Here is my controller action:

def handleModifyProfile2 = { CreditProviderModificationCommand cpmc -> // bind params to the command object if (cpmc.hasErrors()) { flash.message = "Error modifying your profile:" redirect(action: "modifyProfile", params: [creditProvider : cpmc]) } ... 

This is how I try to display errors in my .gsp view:

 <g:hasErrors bean="${creditProvider}"> <div class="errors"> <g:renderErrors bean="${creditProvider}" as="list" /> </div> </g:hasErrors> 

How can I get the errors displayed in the view?

+7
source share
2 answers

You cannot send a command through redirection using params . You have several options:

  • render() in error condition instead of redirect() ing:

     if(cpmc.hasErrors()) { render(view: 'profile', model: [creditProvider: cpmc]) } 

    This is the most common idiom for what you do.

  • Save the command in the session to save it through redirection:

     if(cpmc.hasErrors()) { session.cpmc = cpmc redirect(...) } // and in your action def cpmc = session.cpmc ?: null render(view: 'profile', model: [creditProvider: cpmc]) 

    This parameter is somewhat doubtful. If this is not done correctly, you can pollute the session and leave objects hanging around, occupying memory. However, if everything is done correctly, it can be a decent way to implement post-redirect-get.

+9
source

With Grails 3 (I don't know if this worked before), you can use flash to do this. According to the documentation, the flash will be "cleared at the end of the next request."

I like to use a template like this:

 def save(MyDomain myDomain) { if (myDomain.validate()) { myDomain.save() } else { flash.errors = myDomain.errors } redirect(action: 'edit', id: myDomain.id) } def edit(MyDomain myDomain) { if (flash.errors) { myDomain.errors = (Errors) flash.errors } return [myDomain: myDomain] } 

I do not like to use render() for this kind of error handling, because it makes the URLs displayed in the browser incompatible with the displayed page. This is broken when users set bookmarks, for example.

0
source

All Articles