代码之家  ›  专栏  ›  技术社区  ›  James McMahon

在ExtJs中,在将记录同步到商店后,我如何获得id?

  •  2
  • James McMahon  · 技术社区  · 14 年前

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

    例如,如果我有 PersonStore 设置为autosync,然后我根据用户填写的表格添加一个新人,我可以通过以下操作将新记录添加到商店中;

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

    由于autosync设置为true,这会将新值发送到后端,在那里它会被分配一个id。然后,后端会用新创建的记录的id响应客户端。

    我如何在客户端代码中获得这个新创建的记录的id? 我本来以为结果会包含它,但结果的id仍然设置为null。

    1 回复  |  直到 14 年前
        1
  •  8
  •   Izhaki    14 年前

    当服务器端设置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,
        );
    }
    

    然后在你的应用程序中,你的控制器应该挂接商店写入事件。类似于以下内容:

    init: function() {
    
        this.getTasksStore().on({
            write:  this.onStoreWrite,
            scope:  this            
        });
    },
    

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

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