【发布时间】:2013-04-03 20:51:17
【问题描述】:
我有两个模型:Book belongsTo Author。让我们调查一下作者数据与书籍数据一起从服务器到 ExtJs 并返回的过程。服务器向 ExtJs 发送以下嵌套数据:
{
success : true,
data: {
id: '23',
name: 'JavaScript - The definitive guide'
author: { // <<-- nested author data
id: '45',
name: 'David Flanagan',
}
}
}
在 ExtJs 方面,数据通过以下模型处理:
Ext.define('My.models.Book', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
'id',,
'name',
{name: 'author_id', mapping: 'Author.id'}, // <<-- flat author data
],
proxy: {
type: 'ajax',
api: {
read: 'My/Books/index',
create: 'My/Books/create',
update: 'My/Books/update',
destroy: 'My/Books/delete'
},
reader: {
type: 'json',
root: 'data',
},
writer: {
type: 'json',
root: 'data',
},
},
associatinons: [{
type: 'belongsTo',
model: 'My.models.Author',
associationKey: 'Author',
}]
});
感谢在Book 模型({name: 'author_id', mapping: 'Author.id'})的author_id 字段上映射Author.id,我能够将作者的数据加载到以下用于编辑书籍数据的表单:
Ext.define('My.views.books.Form', {
extend: 'Ext.form.Panel',
initComponent: function () {
var me = this;
me.items = [{
xtype: 'container',
layout:'anchor',
defaults:{
anchor: '95%'
},
items:[{
xtype: 'textfield',
fieldLabel: 'Book title',
name: 'name'
},{
xtype: 'combo',
fieldLabel: 'Author',
name: 'author_id', // <<-- flat author data
store: ...
}]
}];
me.buttons = [{
text: 'Save',
scope: me,
handler: me.onSave
}];
me.callParent(arguments);
},
...
});
当然有一个专门用于作者的模型,但是当我需要一次将书籍和作者数据加载到一个表单中时,我(暂时)看不到上面显示的其他可能性(当然告诉我拜托,如果有更好的解决方案。
问题来了:我会从combo中选择一些其他作者,然后我会保存表单。随着书籍记录变脏(author_id 现在显示为Book 模型字段),将向'My/Books/update' URL 提出请求(这很好,我正在编辑书籍)并将以下数据发送到服务器:
{
data: {
id: '23',
name: 'JavaScript - The definitive guide',
author_id: '78' // <<-- flat author data
}
}
返回到服务器的数据与发送到 ExtJs 的结构不同,必须进行某种翻译,例如:
$data['Author']['id'] = @$data['author_id'];
unset($data['author_id']);
我在问:是否可以通过 ExtJs 形式处理数据,使它们以与来自服务器的相同结构返回到服务器?怎么样?
here、here 和 here 已经以某种方式讨论了这个问题,但这些讨论都没有明确回答。
提前感谢您的帮助! :)
【问题讨论】:
标签: forms extjs4 save associations