ExtJS: Two way binding between Grid & Form

2020-04-21 01:34发布

问题:

I am trying to learn ExtJS and am sort of stuck at a place. I want to create a screen with a grid on top and a form at the bottom. I want to bind them both with each other so that when I select a row from Grid, the form fields are populated (with the same record in the grid) and when I change anything in either grid or form, the other side is updated.

So far, I have a view with a grid and a form. I have a store that provides data to the grid. I am stuck here. How to do two way binding between form and grid. I tried google and found a few samples here and here but they all are one way binding. i.e. if I do the following on grid:

           listeners: {

                selectionchange: function(model, records) {
                    var rec = records[0];
                    var form = Ext.getCmp('chartofaccountsForm');
                    form.loadRecord(rec);
                }
            }

it only populates the form with currently selected record but when I updated the record in form, the grid is not updated.

Can anyone help me by pointing me to the right direction? Any tutorial, or blog post would be very helpful

回答1:

Try this example:

Ext.widget('container',{
        width: 600,
        hight: 800,
        renderTo: Ext.getBody(),
        viewModel: {
            formulas: {
                selection: {
                    bind: '{g.selection}',
                    get: function(selection){
                        return selection;
                    }
                }
            }
        },
        items: [
            {
                xtype: 'grid',
                title: 'Grid',
                reference: 'g',
                store: {
                    type: 'store',
                    fields: ['id', 'name'],
                    data: [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}]
                },
                columns: [
                    {dataIndex: 'id', header: 'ID'},
                    {dataIndex: 'name', header: 'Name'}
                ]
            },
            {
                xtype: 'form',
                title: 'Form',
                items: [
                    {
                        xtype: 'displayfield',
                        fieldLabel: 'ID',
                        bind: '{selection.id}'
                    },
                    {
                        xtype: 'textfield',
                        fieldLabel: 'Name',
                        bind: '{selection.name}'
                    }
                ],
                bind: {
                    hidden: '{!selection}'
                }
            }
        ]

    });

https://fiddle.sencha.com/#fiddle/179d