Oscar
Oscar

Reputation: 13960

Proper way to update a model instance with rest proxy in Sencha Touch 2

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?

Upvotes: 1

Views: 1159

Answers (1)

Stuart
Stuart

Reputation: 3258

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

Upvotes: 1

Related Questions