1

In my Marionette.CompositeView it will be possible to create a new model making a put request to the server(1).
The put request is ok, but when I add the new model to the collection, the new model misses the id which is created by the server.
How should I fix this issue?

Should
1) the POST request send the id to the client or
2) I have to make another request from the client to get the id?


(1)

return Marionette.CompositeView.extend({

    submitForm: function (event) {
            this.textAreaElement = this.$el.find('[data-tid="announcement"]');
            this.messageModel = new MessageModel();
            this.messageModel.save({
                message: this.textAreaElement.val()
            }, {
                wait: true,
                success: this.onSuccess,
                error: this.onError
            });
   },

    onSuccess: function () {
        console.log(this.messageModel.get('id')); // undefined
        this.collection.add(this.messageModel); // I need to get also the id of the following model
                                                // which is created by the server
    }

});
js999
  • 2,063
  • 4
  • 26
  • 34

3 Answers3

1

Your server needs to respond to the POST with JSON representing the saved model, including the ID (or just the the ID). For example, return {"id": "123"} and backbone will update the model for you.

Tony Abou-Assaleh
  • 3,000
  • 2
  • 25
  • 37
0

In the options you pass to save() add wait:true. The attributes of the model (including id) will then be set to whatever json object the server returns for this request.

Robert Levy
  • 28,747
  • 6
  • 62
  • 94
  • I did update my question putting the option `wait: true`. Can you check it? thanks. Unforunatilly when I get the id in onSuccess function, the id is undefined. Should it be a server issue? – js999 Jul 26 '12 at 07:52
  • Yeah, the server needs to send down the ID and any other values you want the model to have – Robert Levy Jul 26 '12 at 11:00
0

Backbone->Create and of course, like @Robert said, you can add wait:true so that your view is not updated until the server sends back your model (including the ID)

Claudiu Hojda
  • 1,021
  • 9
  • 14
  • I did update my question putting the option `wait: true`. Unforunatilly when I get the id in onSuccess function, the id is undefined. Should it be a server issue? – js999 Jul 26 '12 at 07:52
  • I think yes, you should POST manually to check the response from it. What server are you using? – Claudiu Hojda Jul 26 '12 at 10:54
  • I asked a similar question yesterday and got the answer I needed. http://stackoverflow.com/questions/11628076/backbone-js-getting-id-from-collection-create – Joe Jul 26 '12 at 22:32