PDA

View Full Version : Adding model instance to store with "id" property



AndiDog
11 Jun 2012, 8:01 AM
My model and store are defined as follows:

Ext.define('TestApp.model.Contact', {
extend: 'Ext.data.Model',
config: {
fields: ['firstName', 'lastName', 'id'],

proxy: {
type: 'localstorage',
id : 'some-contacts'
}
}
})

Ext.define('TestApp.store.Contacts', {
extend: 'Ext.data.Store',
requires: ['TestApp.model.Contact'],
config: {
model: 'TestApp.model.Contact'
}
})

My model instances are loaded from a web service so they already have an "id" property which I want to reuse. In the following example, the add() call succeeds if I pass the given "id" value, but then the instance does not get saved (count of data objects after another load() goes back to what it was).


var store = Ext.getStore("Contacts")
store.load()
alert(store.getData().length)

// Fine, but auto-creates ID:
store.add({firstName: "James", lastName: "Jameson"})
// Neither of these work
store.add({firstName: "James", lastName: "Jameson", id: 5})
store.add(new TestApp.model.Contact({firstName: "James", lastName: "Jameson"}, 38))

alert(store.getData().length)
store.sync()
alert(store.getData().length)
store.load()
alert(store.getData().length)

How can I use my own ID field? (And btw, this should not fail silently!)

scottmartin
11 Jun 2012, 9:35 AM
If your id is populated and it is not considered a phantom record, it is considered an update.

btw, is there a reason for: id : 'some-contacts' in your proxy?

Scott.

dedoz
11 Jun 2012, 9:54 AM
you can set another property as id with model config idProperty like "myId".

or you can manually set record to phantom (record.phantom = true) meaning records is new and wasnt been saved

AndiDog
11 Jun 2012, 10:51 AM
So if it's considered an update (makes sense), and that instance does not exist yet, shouldn't it be inserted (what the function name add() suggests)?! That is what does not work in my example.

I tried the following now and both variants work:

new TestApp.model.Contact({firstName: "James", lastName: "Jameson"}, 38).save()

new TestApp.model.Contact({firstName: "James", lastName: "Jameson", id: "250"}).save()

Is this the preferred way to do it?

AndiDog
11 Jun 2012, 12:17 PM
Oh, and for the "id" property, I have it there because the docs read as follows:

The only configuration we need to pass to the LocalStorage proxy is an id (http://docs.sencha.com/ext-js/4-0/#%21/api/Ext.data.proxy.LocalStorage-cfg-id). This is important as it separates the Model data in this Proxy from all others. The localStorage API puts all data into a single shared namespace, so by setting an id we enable LocalStorageProxy to manage the saved Search data.