Tobi
Tobi

Reputation: 2040

Grails data binding field exclusion

I am using Grails 2.5 and use Grails databinding in request methods.
For a basic example of the situation consider the following:

Domain class

class Product {
  String field1
  String privateField
}

Controller

class ProductController {
  def update(Product productInstance) {
     productInstance.save()
  }
}

If I pass an existing Product to the controller like

{"id":3, "privateField":"newValue","field1":"whatever"}

the old value of privateField is overwritten. I want to enforce, that privateField is never bound from a request and avoid checking if the field is dirty.
Is there a mechanism in Grails to achieve this?

If I have to do the dirty check, how can I discard the new value and use the old one?

Upvotes: 1

Views: 492

Answers (2)

billjamesdev
billjamesdev

Reputation: 14642

Pretty sure there's a "bindable" constraint.
http://grails.github.io/grails-doc/2.5.x/ref/Constraints/bindable.html

class Product {
  String field1
  String privateField

  static constraints = {
      privateField bindable: false
  }
}

Should keep that field from binding automatically.

Upvotes: 4

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9885

You can enforce which values are bound, but you'll need to change your method signature to get more control of the data binding process.

class ProductController {
  def update() {
     def productInstance = Product.get(params.id)

     bindData(productInstance, params, [exclude: ['privateField']]
     productInstance.save()
  }
}

Upvotes: 1

Related Questions