jcm
jcm

Reputation: 1789

Grails validation error from service method

I have a method in a service class that creates an object:

def createContent (fileName, description) {

    def content = new Content(
        fileName:fileName,
        description:description,
    ).save()
}

Neither of those properties are nullable. How can I pass the validation errors back to be displayed? I've tried flash.message and render, both of which don't work from within service classes. I also tried .save(failOnError:true) which displayed a long list of errors.

Upvotes: 1

Views: 1926

Answers (1)

emstol
emstol

Reputation: 6206

Simplifying everything it should look like this.

Service method:

def createContent (fileName, description) {
    //creating an object to save
    def content = new Content(
        fileName:fileName,
        description:description,
    )

    //saving the object
    //if saved then savedContent is saved domain with generated id
    //if not saved then savedContent is null and content has validation information inside
    def savedContent = content.save()

    if (savedContent != null) {
        return savedContent
    } else {
        return content
    }
}

Now in controller:

def someAction = {
    ...
    def content = someService.createContent (fileName, description)
    if (content.hasErrors()) {
        //not saved
        //render create page once again and use content object to render errors
        render(view:'someAction', model:[content:content])
    } else {
        //saved
        //redirect to show page or something
        redirect(action:'show', model:[id:content.id])
    }
}

And someAction.gsp:

<g:hasErrors bean="${content}">
   <g:renderErrors bean="${content}" as="list" />
</g:hasErrors>

And in general you should look through this: Grails validation doc

Upvotes: 5

Related Questions