Validating List Objects in Grails

I am trying to get grails to check the contents of a list of objects, it might be easier if you show the code first:

class Item { Contact recipient = new Contact() List extraRecipients = [] static hasMany = [ extraRecipients:Contact ] static constraints = {} static embedded = ['recipient'] } class Contact { String name String email static constraints = { name(blank:false) email(email:true, blank:false) } } 

Basically, I have the only Contact ('recipient') required, this works fine:

 def i = new Item() // will be false assert !i.validate() // will contain a error for 'recipient.name' and 'recipient.email' i.errors 

What I would like to do also checks any of the attached Contact objects in "extraRecipients" in such a way that:

 def i = new Item() i.recipient = new Contact(name:'a name',email:' email@example.com ') // should be true as all the contact are valid assert i.validate() i.extraRecipients << new Contact() // empty invalid object // should now fail validation assert !i.validate() 

Is it possible or just need to extraRecipients over the collection in my controller and call validate() for each object in extraRecipients ?

+4
source share
1 answer

If I understand the question correctly, you want the error to appear on the object of the Item object (as an error for the extraRecipients property, instead of allowing cascading storage to throw a validation error for individual contact elements in extraRecipients, right?

If so, you can use a custom validator in your Item constraints. Something like this (this has not been verified, but should be close):

 static constraints = { extraRecipients( validator: { recipients -> recipients.every { it.validate() } } ) } 

You may become more attractive than the error message, which could potentially mean in the result line an error that the recipient failed, but this is the main way to do this.

+8
source

Source: https://habr.com/ru/post/1286712/


All Articles