Đinh Hồng Châu
Đinh Hồng Châu

Reputation: 5440

Grails: Validate domain object failed when creating new object

When I created a new domain object and call save command after validating, it failed and return an error that the id of object is null! But my Domain's id will be generated by database sequence automatically, so I didn't pass the Id value to it. How can I solve it?! Here is my code:

if (person.validate()) { // It is always false here
    person.save()
} else {
    // something here
}

Thank you so much!

Upvotes: 0

Views: 829

Answers (3)

Burt Beckwith
Burt Beckwith

Reputation: 75681

Without your code it's hard to tell, but I'm assuming you have no constraints so you aren't expecting any issues. But there's an implicit not-null constraint for all fields unless you override it with nullable: true so that's probably what's failing.

The reason the id is null is that it's only assigned after a successful save() call.

Upvotes: 2

Hoàng Long
Hoàng Long

Reputation: 10848

Actually, you don't need to call validate() before save(), since save() implicitly call validate before it save the object. You can do it like this:

if (person.save(flush:true)) {
   // Report success
} else {
   // Report error
   person.errors.each {
        println it
   }
}

About the cause of your problem, I think it's impossible to say without knowing your domain object.

Upvotes: 0

Houcem Berrayana
Houcem Berrayana

Reputation: 3080

I guess you have added a field called id in you Person Model class. Normally Grails will do it for you so you don't have to add it

Upvotes: 0

Related Questions