tags:

views:

80

answers:

3

I have a custom validator like -

validator: { userEmail, userAccount ->

   if (userAccount.authenticationChannel == "ABC") {
      boolean valid = true;
      UserAccount.withNewSession {
      if (UserAccount.findByEmail(userEmail)){
         valid = false;
      }
      else if (UserAccount.findByName(userEmail)) {
         valid = false;
      }

...

So basically, I need some validation based on some condition and in my validation I need to execute a query.

But, now if I do -

def admin = new UserAccount(firstname:'Admin',email:'[email protected]')


admin.save(flush:true)


admin.addToAuthorities("ADMIN").save(flush:true)

It fails.

Grails is running the validation, even on update and since email exists validation fails. How is this different if I do

email {unique:true}

Is Grails saying that I cannot write a custom validator which checks uniqueness.

+1  A: 

It fails.

If you provide any exception or fail stacktrace, it would be much easier to help you.

Olexandr
A: 

An alternative might be to do the checks in the save method.

def save = {
  ..
  if (some_checks_succeed(userEmail, userAccount)) {
    admin.save(flush: true)
  }
  ..
}

def some_checks_succeed = { String userEmail, String userAccount ->
  boolean valid = true;
  if (userAccount.authenticationChannel == "ABC") {
    UserAccount.withNewSession {
    if (UserAccount.findByEmail(userEmail)) {
     valid = false;
    } else if (UserAccount.findByName(userEmail)) {
     valid = false;
    }

    ..
  }

  return valid
}

Some modifications might be necessary, but the above code gives you an example

Molske
A: 

Thanks. I could get this to work.The admin.save() calls validation both on insert and update. I handled both the cases (insert and update) and was able to get this working.

Thanks

RockyJ