13

Suppose I have User domain class and RegistrationCommand class. So when user is registering on website there are two steps for data validation:

  1. RegistrationCommand constraints validation.
  2. User domain object constrains validation.

Controller action receive command object and pass it to view in a model after computing. So, I want to join domain objects' validation errors with command objects' errors and pass them as a part of command object. What is the best way to do that?

Yarovoy
  • 649
  • 7
  • 17

3 Answers3

10

I think the full answer is:

if (!user.validate() || !user.save(true))
{
    if (user.errors.hasErrors())
    {
        user.errors.allErrors.each {FieldError error ->
            final String field = error.field?.replace('profile.', '')
            final String code = "registrationCommand.$field.$error.code"
            command.errors.rejectValue(field, code)
        }
    }
    chain(action: 'registration', model: [command: command])
    return
}
Yarovoy
  • 649
  • 7
  • 17
5

I did the following for my project and found it to be more cleaner!

domain.errors.each {
  cmdObject.errors.reject(it.code, g.message(error: it))
} 
uladzimir
  • 5,639
  • 6
  • 31
  • 50
Karthick AK
  • 208
  • 2
  • 5
3

You could probably use the reject mechanism, i.e.

domainObjects.errors.each{
     commandObject.errors.reject( ... )
}

http://grails.org/doc/1.3.7/ref/Domain%20Classes/errors.html

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Tomas Lin
  • 3,532
  • 1
  • 22
  • 19
  • That should be the best way. But I can't think out how to migrate errors' codes from Domain object to Command object. Suppose, in Domain object I have these auto-generated error codes in FieldError object: `com.site.account.Profile.signature.blank.com.site.account.User.profile.signature … com.site.account.Profile.signature.blank … profile.signature.blank blank.com.site.account.User.profile.signature blank.profile.signature blank.signature blank.java.lang.String blank` In result I want to transform them into this code: `RegistrationCommand.signature.blank` How can I achieve that? – Yarovoy Jan 06 '12 at 15:06