Anthony
Anthony

Reputation: 36008

How to restrict properties for a domain being set from params

I've got several properties in my domain class. However, I only want few of them to be set via the params object. What is a good way to do this?

Example:

Domain

class Color {
  String name
  String shade //don't want this set by params
}

controller

class ColorController { 
  def save() {
     json {
       def c = new Color(params?.color)
       c.save(flush: true)
       //..more code
     }
  }
}

If someone sends a request like:

  {"color": 
    {name: "red",
     shade: "light"
    }
  }

then user can change the shade property. How can I stop this?

Upvotes: 0

Views: 277

Answers (2)

Jeff Smith
Jeff Smith

Reputation: 705

Grails provides a bindData method on the controller to give you fine grained control of data-binding. For your example you could write this as:

class ColorController { 
  def save() {
     json {
       def c = new Color()
       bindData(c, params, [include: 'name'])
       c.save(flush: true)
       //..more code
     }
  }
}

In this case, only the 'name' field would be set on the c instance before attempting to save.

If you want to to additional validation on the incoming params, I would also suggest looking into using a Command Object for the data binding.

Upvotes: 1

Kelly
Kelly

Reputation: 3709

You could probably do one of a couple of things:

  1. If it is many properties, create a transient beforeInsert() {} and/or transient beforeUpdate() {} method in your domain class and handle setting (or not) the properties.
  2. If only a few, override the setters in the domain class.

Since Groovy makes me not want to mess with getters and setters unless I absolutely have to, I usually use the beforeInsert and beforeUpdate methods.

Upvotes: 1

Related Questions