1

I can't find a proper way to update an existing model instance using a rest proxy, Sencha Touch always sends a PUT instead of POST to REST backend.

I followed those steps:

Generate a new proyecto from scratch. Then, add a new model using sencha command:

sencha generate model Test id,feld1

Set idProperty and rest proxy inside Test.js model:

idProperty: 'id',
proxy :{
            type: 'rest',
            url: 'http://localhost:3000/products'
}

Add this model to app.js

models: [
        'Test'
]

Then, inside launch function of app.js:

launch: function() {
        var test = Ext.create('test.model.Test');
        test.set('id', '1');
        test.set('feld1', 'some text');
        test.save({
            success: function(){
                console.log('Ok');
            },
            failure: function(){
                console.log('Ko');
            }
        }):
    }

This causes a POST request to the backend server, instead of a PUT, as expected when updating and existing model instance. I'm assuming here that Sencha knows it's an existing instance because idPropertyField (id) is not null or empty.

Request URL:http://localhost:3000/products?_dc=1466427599915
Request Method:POST
Request Payload: {id: "1", feld1: "some text"}

What is the proper way to update an existing model instance in Sencha Touch using a REST proxy? How to make it fire a PUT request instead of POST?

Oscar
  • 13,594
  • 8
  • 47
  • 75

1 Answers1

1

If you set the phantom property of the record to false before saving, it will be picked up as an updated record rather than a new one.

Check out this fiddle as an example: https://fiddle.sencha.com/#fiddle/1cd1

If you look at the Ext.data.Model's save method (http://docs.sencha.com/extjs/6.0.1-classic/src/Model.js-1.html#Ext.data.Model-method-save) you can see how this is determined. Essentially it boils down to this line:

action = dropped ? 'destroy' : (phantom ? 'create' : 'update'), 

There is a similar filtering method in the Ext.data.ProxyStore class which handles this for store syncs - http://docs.sencha.com/extjs/6.0.1-classic/Ext.data.ProxyStore.html#method-filterNew

Stuart
  • 3,258
  • 4
  • 29
  • 39
  • Thanks for your response. Strangely, I tried that before without success, maybe a cached script. Is there a way to make phantom property return false when idProperty is null or empty automatically instead of having to set it manually all the time? – Oscar Jun 21 '16 at 14:51
  • 1
    You could override the set method of the model class and check for the field matching the idProperty and then update phantom to false. – Stuart Jun 22 '16 at 11:59
  • Awesome. Thanks for your time and help. – Oscar Jun 22 '16 at 12:23
  • 1
    No problem. Something that just came to mind if you do override the set method - be aware that it can accept objects as well as field & value! – Stuart Jun 22 '16 at 12:54