Sencha touch保存新记录并更新ID(密钥)

时间:2014-11-03 12:01:01

标签: extjs touch sencha-touch-2

现在我使用此代码保存新的/存在的记录:

var values = this.getFrmDetails().getValues();
var record = this.getFrmDetails().getRecord();
var store  = Ext.getStore('usersStore');
record.set(values);
// Is this a new user?
if (record.data.id==-1)
{
    record.save();
    store.add(record);
}
store.load();
this.getMainView().pop();
  • 此代码运行正常,但始终可以保存&再次加载整个数据,我按id跟踪记录,因此当我添加新记录时,我传递了-1作为ID。

  • 如果不使用store.load(),则在我重新加载应用之前,新记录的ID始终为-1

如何使用在服务器端创建的id更新新记录?

  • 我在PHP服务器端使用REST代理,MySQL数据库。

  • 顺便说一下,在Firebug中,我总是看到PUT有关新/更新的记录。我如何才能让Sencha触摸发送POST仅用于新记录,而PUT仅用于更新现有记录?

  • 我店里有autosync=true

谢谢

2 个答案:

答案 0 :(得分:0)

我找到了解决方案:

var newid=-1;
record.save({success : function(res){newid=res.getId();}});
record.data.id=newid;

PHP方面:

  $sql="SELECT LAST_INSERT_ID() id";
  $rs=mysql_query($sql);
  $db_field = mysql_fetch_assoc($rs);
  echo json_encode(array("success"=>$db_field['id'])); 

答案 1 :(得分:0)

我使用的是C#而不是PHP,但我使用相同的'-1'Id技术。当我在商店中插入记录并与远程同步时,我返回插入的记录,商店从服务响应中获取值。

var store = Ext.getStore('fooStore');
var newFoo = {
    a: 'a',
    b: 'b'
};

store.add(newFoo) // here the record id would be -1
store.sync({
    callback: function () {
        // here the id is the returned from the server
        // this is not needed if you have autoSync, It's just for clearness
    }
});

而我的C#代码结构将是:

function Foo Insert(Foo foo) {
    var myTable = new MyTable(); // In PHP would be different, but I guess that the idea is clear.
    var newRecord = myTable.Insert(foo); // The insert method returns the added record.
    return newRecord;
}

然后,模型或商店定义将返回返回的记录,并且ID将自动更新。如果使用此方法,则无需使用store.load()方法,因为响应具有更新所需的信息。

对于请求POST而不是PUT的类型,您必须在模型/商店代理定义中使用它:

// ...
proxy: {
    // ...
    actionMethods: {
        create: 'POST',
        read: 'POST',
        update: 'POST',
        destroy: 'POST'
    }
    // ...
}
// ...