Josh
Josh

Reputation: 43

How can I make fields of a domain mandatory based on controller action?

Is there a way to make domain fields mandatory depending on which controller action is hit by the user?

Example:

class Color {

  String name
  String shade

  static constraints{
    name nullable: true, blank: true
    shade nullable: true, blank: true
  }
}

class MyController {

  def save1() {
    //here I want only name field to be required
    Color c = new Color(params)
    c.save()
  }

  def save2() {
    //here I want only shade field to be required
    Color c = new Color(params)
    c.save()
  }
}

Upvotes: 2

Views: 89

Answers (2)

cfrick
cfrick

Reputation: 37008

you can use a CommandObject and define your own constraints there

see http://grails.org/doc/latest/guide/theWebLayer.html#commandObjects

e.g.:

@grails.validation.Validateable
class ColorWithName {
    String name
    String shade

    static constraints = { 
        name(nullable: false, blank: false)
    } 
}

class ColorController {

    def save1(ColorWithName color) {
    if (color.hasErrors()) { ...

Upvotes: 0

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27210

One option you have is something like this:

class MyController {

    def save1() {
        //here I want only name field to be required
        def color = new Color(params)
        if(color.validate(['name'])) {
            color.save(validate: false)
        }
    }

    def save2() {
        //here I want only shade field to be required
        def color = new Color(params)
        if(color.validate(['shade'])) {
            color.save(validate: false)
        }
    }
}

Upvotes: 3

Related Questions