Search code examples
extjsextjs7

ExtJS 7 How to select grid row on rightclick


I'd like to both open a context menu and select the right-clicked row in a ExtJS 7 modern grid. The context menu works with the code below. However, I cannot find a way to select the row. The grid.getSelectionModel() seems to be no longer available in ExtJS 7.

// Listener in my Ext.app.ViewController manages to update and show context menu but not to select the row.
onContextMenu: function (e) {
        const grid = this.getView();
        const target = e.getTarget(grid.itemSelector);
        if (target) {
            e.stopEvent();
            const item = Ext.getCmp(target.id);
            if (item) {
                // Would like to select row here with something like grid.getSelectionModel().selectRow(rowindex);
                this.updateMenu(item.getRecord(), item.el, e);
            }
        }
    }

Solution

  • Have a look at the following fiddle sample (Modern toolkit 7.3.1)

    Ext.application({
        name: 'Fiddle',
    
        launch: function () {
            const menu = new Ext.menu.Menu({
                items: [{
                    text: 'Menu Item 1'
                }, {
                    text: 'Menu Item 2'
                }]
            });
    
            Ext.Viewport.add({
                xclass: 'Ext.grid.Grid',
                store: Ext.create('Ext.data.Store', {
                    fields: ['name', 'email', 'phone'],
                    data: [{
                        name: 'Lisa',
                        email: '[email protected]',
                        phone: '555-111-1224'
                    }, {
                        name: 'Bart',
                        email: '[email protected]',
                        phone: '555-222-1234'
                    }]
                }),
    
                columns: [{
                    text: 'Name',
                    dataIndex: 'name',
                    width: 200
                }, {
                    text: 'Email',
                    dataIndex: 'email',
                    width: 250
                }, {
                    text: 'Phone',
                    dataIndex: 'phone',
                    width: 120
                }],
                listeners: {
                    childcontextmenu: function (grid, location) {
                        const {
                            record,
                            event
                        } = location;
                        grid.deselectAll();
                        grid.setSelection(record);
                        menu.showAt(event.getX(), event.getY());
                        event.stopEvent()
                    }
                }
            })
        }
    });