1
votes

I am trying to setup a javascript object such that when it data binds to a new object in the controller, the associated child objects in the DB are pulled based on the id field. This is documented in the Spring data binding as such:

Data binding and Associations

If you have a one-to-one or many-to-one association you can use Grails' data binding capability to update these relationships too. For example if you have an incoming request such as:

/book/save?author.id=20

Grails will automatically detect the .id suffix on the request parameter and look-up the Author instance for the given id when doing data binding such as:

def b = new Book(params)

I want to post a javascript object to the controller as a fully composed object with the child properties. How can I setup the javascript object so that the controller sees the child properties of the object as in the following url (the same as is documented) /book/save?author.id=20?

I have tried this but it doesn't seem to work:

var childObject= function(name, id) {
                this.name = name;
                this.id = id;    
            };

var viewModel = {
    id: 1,
    child: new childObject("Chuck",1)
 }

The controller doesn't see 'child.id' when the viewModel is posted to the controller and automatically fetch the associated record. Am I totally off base thinking it works like this?

Perhaps another way to ask this is how can I serialize a javascript object so that its string representation is "object.property"?

1
Could you add your Domain objects to your code? Also, could you add a println(params) at the beginning of the closure that you're hitting in the controller so we can see what data you are passing to Grails? That would help quite a bit to give you an answer - Tom Hartwell

1 Answers

0
votes

Creating the javascript object as {child :{id:1} } should do what you are trying to achieve. Try something like this to create the required js object

     var dataObj = {};
     var childObj = {};
     childObj['id'] = 1;
     dataObj['child'] =  childObj;
     return dataObj;