Reputation: 36008
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
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
Reputation: 3709
You could probably do one of a couple of things:
transient beforeInsert() {}
and/or transient beforeUpdate() {}
method in your domain class and handle setting (or not) the properties.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