views:

263

answers:

1

Hi, I'm new to grails and I have a problem:

I have this snippet of GSP:

<g:form url="[controller:'main',action:'login']"> 
  <label for="name">Usuario:</label><br/> 
  <input type="text" name="name" /><br/> 
  <label for="pass">Password:</label><br/> 
  <input type="password" name="password"/><br/> 
  <input type="submit" value="Login"/><br/> 
  <g:renderErrors bean="${cmd}"/> 
</g:form>

The Controller (MainController.groovy) uses a Command Object, here's the code for both:

def login = { LoginCommand cmd -> 
  if(cmd.validate()){ 
  redirect(action:'ok') 
  }else{ 
  render(view:'index',model:[cmd:cmd]) 
  } 
  } 

class LoginCommand { 

        String name 
        String password 

        static constraints = { 
                name(blank:false,size:5..10) 
                password(blank:false,size:5..10) 
        } 
}

The problem is that when I enter a bad name or pass (blank or outside the range) it shows me 4 errors, two for the password and two for the username. They are the same, but duplicated.

I found that creating a method "bool validateCommand(){ name && password }" and replacing it for command.validate() does not throw duplicates, but I want to use the constraints features of Grails to keep things DRY.

Any idea why this happens? Thanks so much!

+6  A: 

When you inject command objects into controller actions, Grails executes validate() automatically, so there is no need to call it manually. Try

if(!cmd.hasErrors())

instead of

if(cmd.validate())

It seems, that every call to validate() adds new (duplicate) errors to the command object. IMHO this shouldn't happen and probably is a bug in Grails. You should consider reporting this issue.

Daniel Rinser
This just saved my sanity. thank you
Johann Zacharee