CRUD in Ext JS 6 Grid:

Here, you will learn how to implement CRUD operation in Ext JS 6

We created our first Ext JS 6 application in First Ext JS Application section. Here, we will continue from there and will add grid view to list all students with Add and Remove buttons which will look like below.

CRUD in Extjs grid

Create Model:

Let's start with model first. Create Student.js file into app -> model folder and create School.model.Student class as shown below.

Ext JS Form CRUD

Ext.define('School.model.Student', {
    
    extend: 'Ext.data.Model',
    idProperty:'Id',
    schema: {
        namespace: 'School.model'
    },
    fields: [
        { name: 'Id', type: 'int', defaultValue: 0},
        { name: 'firstName', type: 'string' },
        { name: 'middleName', type: 'string' },
        { name: 'lastName', type: 'string' },
        { name: 'birthDate', type: 'date' },
        { name: 'address1', type: 'string' },
        { name: 'address2', type: 'string' },
        { name: 'city', type: 'string' },
        { name: 'state', type: 'string' }
    ],
    
    validations: [{
        type: 'presence',
        field: 'firstName'
    }]

});

Create Grid View:

Now, let's create a grid view using classic toolkit of Ext JS 6. So, create student folder into classic -> src -> view folder and then add StudentList.js file as shown below.

Ext JS grid CRUD

In the above StudentList.js file, create custom StudentList grid view by deriving Ext.grid.Panel and define grid columns as shown below.

Ext.define('School.view.student.StudentList', {
    extend: 'Ext.grid.Panel',
    xtype: 'studentList',

    title: 'Student List',

    controller: 'student-list',
    viewModel: { type: 'studentviewmodel' },
    reference:'studentlistgrid',
    selType: 'rowmodel',
    selModel:
    {
        mode: 'SINGLE'
    },
    viewConfig:
    {
        stripeRows: true
    },
    listeners: {
        selectionchange: 'onSelectionChange'
    },
    bind: {
        store: '{StudentListStore}'
    },
    initComponent: function () {
        Ext.apply(this,
        {
            plugins: [Ext.create('Ext.grid.plugin.RowEditing',
            {
                clicksToEdit: 2
            })],

            columns: [{
                text: "Id",
                dataIndex: 'Id',
                hidden: false,
                width: 35
            },
            {
                text: "First Name",
                flex: 1,
                dataIndex: 'firstName',
                editor:
                {
                    // defaults to textfield if no xtype is supplied
                    allowBlank: false
                }
            },
            {
                text: "Middle Name",
                flex: 1,
                dataIndex: 'middleName',
                editor:
                {
                    allowBlank: true
                }
            },
            {
                text: "Last Name",
                flex: 1,
                dataIndex: 'lastName',
                editor:
                {
                    allowBlank: true
                }
            },
            {
                xtype: 'datecolumn',
                header: "Birth Date",
                width: 135,
                dataIndex: 'birthDate',
                editor:
                {
                    xtype: 'datefield',
                    allowBlank: true
                },
                renderer: Ext.util.Format.dateRenderer('d/m/Y')
            },
            {
                text: "City",
                flex: 1,
                dataIndex: 'city',
                editor:
                {
                    allowBlank: true
                }
            },
            {
                text: "State",
                flex: 1,
                dataIndex: 'state',
                editor:
                {
                    allowBlank: true
                }
            }],
            tbar: [{
                text: 'Add Student',
                iconCls: 'fa-plus',
                handler: 'onAddClick'
            }, {
                itemId: 'removeStudent',
                text: 'Remove Student',
                iconCls: 'fa-times',
                reference: 'btnRemoveStudent',
                handler: 'onRemoveClick',
                disabled: true
            }]
        });

        this.callParent(arguments);
    }
});

In the above grid, it includes two important configs controller and viewModel. The controller config specifies the controller class for this grid view which will handle events of this view. The viewModel config specifies the ViewModel class which includes store for this grid.

Create ViewModel:

Now, create StudentViewModel class for the StudentList grid in app -> view -> student folder as shown below.

Ext JS grid CRUD

Now, define StudentViewModel class as shown below.

Ext.define('School.view.student.StudentViewModel', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.studentviewmodel',
    stores: {
        StudentListStore: {
            model: 'School.model.Student',
            autoLoad: true,
            autoSync: true,
            proxy:
            {
                type: 'rest',
                reader:
                {
                    rootProperty: 'data',
                    type: 'json'
                },
                url: '/api/student',
                writer: {
                    type: 'json',
                    dateFormat: 'd/m/Y',
                    writeAllFields: true
                }
            }
        }

    }
});

As you can see, the School.view.student.StudentViewModel includes store which will be bound to grid view. The autoSync and autoLoad configs are set to true in StudentListStore so that grid will display data as soon as it load records and also it will update or delete records once it changed by user.

Create ViewController:

Create StudentViewController.js into app -> view -> student folder.

Ext JS grid CRUD

Now, define StudentViewController class as shown below.


Ext.define('School.view.student.StudentListController', {
    extend: 'Ext.app.ViewController',

    alias: 'controller.student-list',

    onAddClick: function (sender, record) {

        
        var studentGrid = this.getView();
        var studentStore = studentGrid.getStore();

        //adding dummy student
        var studentModel = Ext.create('School.model.Student');
        studentModel.set("Id", 0);
        studentModel.set("firstName", "New Student");
        studentModel.set("middleName", "");
        studentModel.set("lastName", "");
        studentModel.set("birthDate", "");
        studentModel.set("city", "");
        studentModel.set("state", "");

        studentStore.insert(0,studentModel);
    },

    onLoadClick: function (sender, record) {
        var studentStore = this.getView().getStore();
        studentStore.load();
    },

    onRemoveClick: function (sender, record) {
        var studentGrid = this.getView();
        var studentStore = studentGrid.getStore();

        //delete selected rows if selModel is checkboxmodel
        var selectedRows = studentGrid.getSelectionModel().getSelection();

        studentStore.remove(selectedRows);
    },

    onSelectionChange: function (sender, record, isSelected) {
        var removeBtn = this.lookupReference('btnRemoveStudent');
        if(record.length)
            removeBtn.setDisabled(false);
        else
            removeBtn.setDisabled(true);
    }
});

Thus, you can implement CRUD in grid in Ext JS 6 MVVM architecture. Click Live Example below to see the whole example code in MVVM folder structure.

Live Example