validationgrailsgsp

Returning errors to gsp page in Grails after checking for hasErrors and Validating


I'm building this web app that works with user profiles. A user edit a profile and if he enters wrong data, the profile shows the invalid fields in red and shows the message. Very simple scenario. But for some reasons it doesn't work the way I assumed. I might be missing something somewhere. Here is what I do in my controller.

As you can see in the code below, I create a new Profile, I bind the params to it using an include list to only bind those params that profile accepts, and then call hasErrors on the profile instance. In debug mode, I can see that myProfile has errors when the user enters something wrong, but when I get back to the editProfile page, it doesn't show what field has the error. my gsp form has the render error tag and also hasError for each field.

def update (){

   def myProfile = new Profile()
   dataBind(params, myProfile, include:[.....])

   if (myProfile.hasErrors()){ 
      respond myUser.errors, view: 'editProfile'             
      return
   } 
   else{
      redirect(action:"viewProfile")
   }
} 

My gsp is something like this, I don't have access to my home computer right now to post the exact gsp page:

<g:hasErrors bean="${myUser}" field="name">
    <g:message error="${myUser.errors.getFieldErrors("name")}" />
</g:hasErrors>

Solution

  • Instead of trying to pass the errors back, pass the entire object to your gsp. Assuming the bean you have in your gsp page is 'myUser', then this is what the render statement should be:

    render view: 'editProfile', model: [myUser: myProfile]