在ExtJs中,如何在将记录同步到商店后获取ID?

Jam*_*hon 2 extjs store extjs4

如果我在ExtJs 4下有一个商店,如何在同步发生后从新添加的记录中获取id?

例如,如果我PersonStore设置为自动同步并且我根据用户填写的表单添加新人,我可以通过执行以下操作将新记录添加到商店;

var values = button.up('form').getForm().getValues(),
    store = Ext.StoreMgr.lookup('PersonStore'),
    result;

result = store.add(values);
Run Code Online (Sandbox Code Playgroud)

由于autosync设置为true,因此将新值发送到后端,在后端为其分配id.然后,后端使用新创建的记录的id响应客户端.

如何在客户端代码中获取此新创建记录的ID?我假设结果将包含它,但结果仍然将id设置为null.

Izh*_*aki 8

当服务器端是设置id的那个时,工作流是这样的:

  • 记录已添加到商店,但未分配ID.
  • 存储同步,因此正在向服务器发送创建请求.
  • 服务器返回已发送的记录,并设置了id属性.
  • ExtJS查看返回的记录,如果它设置了id,则将其分配给记录.

顺便提一下,请注意,对于所有CRUD操作,只要id匹配,就会使用从服务器返回的数据更新商店记录.在新创建的记录的情况下,ExtJS有一个internalId机制来确定返回的记录是发送的记录,但是设置了id.

服务器端代码可能如下所示:

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,
    );
}
Run Code Online (Sandbox Code Playgroud)

然后在您的应用程序中,您的控制器应该挂钩商店写入事件.像这样的东西:

init: function() {

    this.getTasksStore().on({
        write:  this.onStoreWrite,
        scope:  this            
    });
},
Run Code Online (Sandbox Code Playgroud)

在该函数中,您可以检查返回的记录(我假设data是读者的根):

onStoreWrite: function ( aStore, aOperation )
{
        var iRecord = aOperation.response.result.data;
        console.log(iRecord.id);

},
Run Code Online (Sandbox Code Playgroud)