开发者

Grails validation issue on multi-domain association?

开发者 https://www.devze.com 2023-01-21 04:17 出处:网络
I need to validate save action between 3 domains, here is relationship : User - JobProcess : one-to-many, JobProcess - Heatmap : one-to-many.

I need to validate save action between 3 domains, here is relationship :

User - JobProcess : one-to-many, JobProcess - Heatmap : one-to-many.

User { static hasMany = [ jobs : JobProcess ] ... }
JobProcess { static hasMany = [ heatmaps : Heatmap ] ... User script ... }
Heatmap { static belongsTo = JobProcess ... JobProcess job ... }

I'm using Exceptions to control validation flow, here is my validation class :

class ValidationException extends RuntimeException {
  Object invalidObject
  ValidationException(String message, Object invalidObject) {
    super(message)
    this.invalidObject = invalidObject
  }
}

I also build a service class to abstract Heatmap operations (开发者_StackOverflowand binds params data to object) :

  def addJob(params) {

    def user = User.findById(params.user_id)

    if (user) {

    def heatmap = new Heatmap(params)

    def process = new JobProcess(params)

        process.addToHeatmaps(heatmap)
        user.addToJobs(process)

    if (user.save()) {
      return heatmap
    } else {
       throw new ValidationException("Invalid form", heatmap )
      }
    }
 }

And my controller :

  try {
    def heatmap= HeatmapService.addJob(params)
      flash.message = "Running new process : $heatmap.job}"
      redirect(uri:'/')
  } catch (ValidationException che) {
    flash.message = "Validation Failed ${che.message}"
    render(view:'create', model:[heatmap:che.invalidObject])
  }

My first issue : I have no error validation by using : user.save() - why no validation are performs?

I can fix this issue buy updating if (user.save()) by : if (heatmap.validate() && user.save()).

Is there a better way to proceed ?

My second issue : my redirect isn't triggering invalid-post exception.

I'm redirected to my create view, but all my fields are blank (I lost all fields information) and no validation errors.

Nevertheless, I'm using model:[heatmap:che.invalidObject].

With the exception, I'm passing back the invalidObject, so my create view should display the exact validation errors ? What's wrong ?

Thanks


I find my issue, it's due to my GSP view, I was using the wrong bean :

<td valign="top" class="value ${hasErrors(bean: heatmapInstance, field: 'project_name', 'errors')}">

So, I updated to heatmap, and now I get my error validation :

<td valign="top" class="value ${hasErrors(bean: heatmap, field: 'project_name', 'errors')}">

Thanks Victor.

0

精彩评论

暂无评论...
验证码 换一张
取 消