问题
If I have a store under ExtJs 4, how do I get an id from a newly added record after a sync occurs?
For example, if I have a PersonStore
set to autosync and I add a new person based on a form filled out by the users, I can add the new record to the store by doing the following;
var values = button.up('form').getForm().getValues(),
store = Ext.StoreMgr.lookup('PersonStore'),
result;
result = store.add(values);
Since autosync is set to true, this sends over the new value to the backend where it is assigned an id. The backend then responds to the client with the id of the newly created record.
How do I get the id for this newly created record in my client side code? I had assumed that result would contain it, but result still has id set to null.
回答1:
When the server side is the one setting the id, the workflow is this:
- Record added to the store without an id being assigned.
- Store syncs, so a Create request is being sent to the server.
- Server returns the sent record, with an id property set.
- ExtJS looks at the returned record and if it has an id set, it assignes it to the record.
Notice, by the way, that for all CRUD operations, the store record will be updated with the data returned from the server so long the id matches. In the case of newly created records, ExtJS has an internalId mechanism to determine that the record returned is the one sent, but with its id set.
The server side code might look something like this:
function Create( $aRecord )
{
global $pdo;
$iInsertClause = InsertClause::FromFields( self::$persistents );
$iStatement = $pdo->prepare( "INSERT INTO Tags $iInsertClause" );
$iStatement->execute( InsertClause::ObjectToParams( $aRecord, self::$persistents ) );
// Inject the id into the record and return it in the reader's root,
// so client side record updates with the new id.
$aRecord->id = $pdo->lastInsertId();
return array(
'success' => true,
'data' => $aRecord,
);
}
Then within your app, your controller should hook on store write events. Something like this:
init: function() {
this.getTasksStore().on({
write: this.onStoreWrite,
scope: this
});
},
And within that function you can inspect the returned record (I assume data
is the reader's root):
onStoreWrite: function ( aStore, aOperation )
{
var iRecord = aOperation.response.result.data;
console.log(iRecord.id);
},
来源:https://stackoverflow.com/questions/11868117/in-extjs-how-do-i-get-an-id-after-syncing-a-record-to-the-store