1

オブジェクトを作成するサービス クラスにメソッドがあります。

def createContent (fileName, description) {

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

これらのプロパティはどちらも null 許容ではありません。検証エラーを返して表示するにはどうすればよいですか? flash.message と render を試しましたが、どちらもサービス クラス内からは機能しません。エラーの長いリストを表示する .save(failOnError:true) も試しました。

4

1 に答える 1

5

すべてを単純化すると、次のようになります。

サービス方法:

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
    }
}

今コントローラーで:

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])
    }
}

そして someAction.gsp:

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

そして、一般的には、これを確認する必要があります: Grails validation doc

于 2011-08-05T07:53:09.030 に答える