articles

Home / DeveloperSection / Articles / Crud Operation in ExtJs

Crud Operation in ExtJs

Hemant Patel 9609 02-Feb-2017

Create tab view with user form and grid view. Grid can be call on trigger click and when we click twice on row data of grid then its set on user form textfields. In user form there is three buttons save,delete and update, that’s perform three operations on button click. All operation perform on database record.

This article also helps of newbie on Extjs. Each design of user form or user record design separately and call on our requirement or need. Its also define how to connect database with MVC controller and perform relevant task.

In the way of development we add a javascript file under project name for call and render application. After this we can add a new folder under our project name (like app). And add three folder under this app folder, model, view, controller.

In view folder add a javascript file named as tabView as your need. In tabView create a tabview like this.


Crud Operation in ExtJs

Crud Operation in ExtJs

Code of html page(index.html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css" rel="stylesheet" />
    <script src="app.js"></script>  //import javascript file by drag and drop
</head>
<body>
</body>
</html>
Code of app.js file 
Ext.application({
    extend: 'Ext.app.Application',   //extend app.Application class
    requires: ['Ext.container.Viewport', 'app.view.TabView'],   // Define your requirements thats you call in this file
    name: 'app',
    launch: function () {
        Ext.create('Ext.container.Viewport', {
            layout: 'anchor',
            items: [{
                xtype: 'TabView'  //Define your type of component,Its define in alias of TabView class
            }]
        });
    }
});
Code of tabView
Ext.define('app.view.TabView', {
    extend: 'Ext.tab.Panel',  //extend tab.Panel class
    requires: ['app.controller.TabController', 'app.view.UserGridView', 'app.view.UserFormView'],  //define requirement of classes
    alias: 'widget.TabView',
    width: 500,
    height: 400,
    //layout: { type: 'absolute', align: 'middle', pack: 'center' },
    bodyPadding: 15,
    controller: 'tabController',  //use controller
    initComponent: function () {
        Ext.apply(this, {
    items: [   //Items of tabview
    {
        title: 'Testing Tab 1',
        width: '100%',
        height: 300,
        margin: '5 5 5 5',
        items: [
        {
            xtype: 'userFormView'  //use userFormView by define alias in userFormView
        }
        ]
    },
    //{
    //    title: 'Testing Tab 2',
    //    items: [
    //    {
    //        xtype: 'userGridView'
    //    }
    //    ],
    //},
    {
        title: 'Testing Tab 2',    //Third tab display details
        html: 'Its a example of card view with tabs,thats provide multiple task at one place using multiple page accessed by tabs',
    }
    ]
    });
    this.callParent(arguments);
    }
});
Code of UserForm
Ext.define('app.view.UserFormView',    //define UserFormView class
{
    extend: 'Ext.form.Panel',   //extend  form.Panel class
    requires: ['app.controller.TabController','app.view.UserWindow'], //define requirements
    border: true,
    padding: 10,
    margin: '5 5 5 5',
    id: 'userForm',
    title: 'User Form',
    layout:   //define layout
    {
        type: 'anchor',
        pack: 'center',
    },
    anchor:'250 250',
    controller: 'tabController',
    alias: 'widget.userFormView',//define alias for direct accessing in other form
    items: [
        {
            xtype: 'hiddenfield',  //use hiddenfield for direct accessing of data without display
            name: 'ID',
            itemId: 'ID',
        },
    {
        xtype: 'trigger',  //use trigger for browse user record in grid and also use as a textfield
        fieldLabel: 'Name',
        name: 'Name',
        itemId: 'txtName',
        
        triggerCls: 'x-form-search-trigger', //for browse symbol
        onTriggerClick: function () {   //define function on trigger click
            var window = Ext.create('app.view.UserWindow');  //create popup window
            window.show();  //call show mwthod
        }
    },
    {
        xtype: 'textfield',
        fieldLabel: 'Father name',
        name: 'FatherName',
        maskRe:/[^@#$%&*0-9^]/,  //validation tool for  write only alphabets in textfield
        itemId: 'txtfatherName',
    },
    {
        xtype: 'datefield',
        fieldLabel: 'D.O.B',
        name: 'DOB',
        maskRe: /[^a-zA-Z0-9~!@#$%^&*+-/^]/, //validation tool for  select only datefield
        itemId: 'dtfield'
    },
    {
        xtype: 'textarea',
        fieldLabel: 'Address',
        name: 'Address',
        itemId: 'txtAreaAddress',
        reference: 'txtAreaAddress'
    },
    {
        xtype: 'textfield',
        fieldLabel: 'Contact Number',
        name: 'PhoneNo',
        maskRe: /[^a-zA-Z!@#$%^&*()_+=-~^]/, //validation tool for insert only numeric data in textfield
        itemId: 'nmbrFldContactNo'
    },
    {
        xtype: 'container', // use container for more than one buttons as your requirement.Its not mandetory thats you use container for buttons or other components
        layout: { type: 'hbox', pack: 'center' },
        width: '100%',
        //margin:'5 5 5 5',
        items: [
        {
            xtype: 'button',
            text: 'Submit',
            width: '25%',
            layout: '',
            itemId: 'saveBtnId',
            listeners: //implement listener for call function of controller
                {
                    click: 'saveClick' //call method of controller on button click
                }
        },
        {
            xtype: 'button',
            name: 'delete',
            width: '25%',
            itemId: 'deleteBtnId',
            text: 'Delete',
            listeners: //implement listener for call function of controller
                {
                    click: 'deleteClick' //call method of controller on button click
                }
        },
        {
            xtype: 'button',
            name: 'update',
            width: '25%',
            itemId: 'updateBtnId',
            text: 'Update',
            listeners: //implement listener for call function of controller
                {
                    click: 'updateClick' //call method of controller on button click
                }
        }
        ]
    }
    ]
});
Code of popup Window
Ext.define('app.view.UserWindow', {  //define UserWindow
    extend: 'Ext.window.Window',  //extend wimdow class
    requires: ['app.controller.TabController', 'app.view.UserGridView'],//requirement of class that use in this page
    controller: 'tabController',//use controller
    title: 'User Details',
    autoScroll:true,
    alias: 'widget.userWindow',//define alias
    height: 400,
    width: 600,
    id: 'popWindow',
    itemID: 'popWindow',
    items: [
    {
        xtype: 'userGridView',  //use grid view
    }
    ]
});
Code of grid view
Ext.define('app.view.UserGridView', {  //define UserGridView class
    extend: 'Ext.grid.Panel',   //extend grid.Panel class
    alias: 'widget.userGridView',  //define alias for direct access
    controller: 'tabController',  //use controller
    width: 700,
    height: 600,
    id: 'userGrid',
    itemId: 'userGrid',
    //autoScroll: true,
    initComponent: function () {  //define initComponent function
        Ext.apply(this, {    //
            store: Ext.create('app.store.TabStore'),  //use store by given its path
            columns: [  
            {
                text: 'Id',
                dataIndex: 'ID',
                itemId: 'Id'
            },
            {
                text: 'Name',
                dataIndex: 'Name',
                itemId: 'name'
            },
            {
                text: 'Father Name',
                dataIndex: 'FatherName',
                itemId: 'fatherName'
            },
            {
                text: 'DOB',
                dataIndex: 'DOB',
                itemId: 'dob',
            },
            {
                text: 'Address',
                dataIndex: 'Address',
                itemId: 'address'
            },
            {
                text: 'Contact No',
                dataIndex: 'ContactNo',
                itemId: 'contactNo'
            }
            ],
            listeners: {   //define listener amd call gridItemSelected function on item double click of user record in grid
                itemdblclick: 'gridItemSelected'
            }
        });
        this.callParent(arguments);
    }
});
Code of model defined for form fields
Ext.define('app.model.TabModel', {   //define model TabModel class
    extend: 'Ext.data.Model',  //extend data.Model class
    fields: [      //define properties of textfields thats use in the user form
        { name: 'ID', type: 'int' },   
        { name: 'Name', type: 'string' },
        { name: 'FatherName', type: 'string' },
        { name: 'DOB', type: 'date', dateFormat: 'MS' },
        { name: 'Address', type: 'string' },
        { name: 'ContactNo', type: 'int' }
    ]
});
Code of Store thats use for data store
Ext.define('app.store.TabStore',  //define TabStore class
    {
        extend: 'Ext.data.Store',   //extend data.Store
        model: 'app.model.TabModel',   //use model and give its path
        storeId: 'tabStore',
        autoLoad: true,
        proxy: {  
            type: 'ajax',
            url: './User/Show',   //give path of Show method in MVC controller
            reader: {
                type: 'json',
                root: 'data'
            }
        }
    });
Code of Controller
Ext.define('app.controller.TabController', {  //define TabController class
    extend: 'Ext.app.ViewController',  //extend app.ViewController class
    alias: 'controller.tabController',   //define alias
    requires: ['app.model.TabModel'],   //define requirement of TabModel class
    views: ['TabView', 'userGridView', 'userFormView', 'app.view.UserWindow'],  //define views that use in this form
   
    saveClick: function () {   //define save function on save button click
        var form = Ext.getCmp('userForm');   //get component of userForm and assign value into form variable
        var values = form.getValues();   //call getValue function by association of form variable and assign into values variable
        Ext.Ajax.request({   //send Ajax request to MVC controller request
            url: './User/Save',   //give path of method define in MVC controller
            method: 'POST',   //use POST method 
            jsonData: values,   //send values in the form of jsonData
            success: function (response) {   //define success function
                var result = Ext.decode(response.responseText);  //decode responseText return by jsondata assign into result variable
                if (result.success === true) {   //check condition if result.success is true
                    Ext.Msg.show({   //create msg show box
                        title: 'EMPLOYEE',  //define title
                        msg: result.message,  //asign result.message value into msg
                        buttons: Ext.Msg.OK,  //create response Ok button
                        icon: Ext.MessageBox.INFORMATION  //create message box and display information
                    });
                }
                else {
                    Ext.Msg.show({
                        title: 'EMPLOYEE',
                        msg: result.message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.MessageBox.ERROR
                    });
                }
            },
            failure: function () {
                Ext.Msg.show({
                    title: 'Record not inserted',
                    msg: result.message,
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
            }
        });
    },
    gridItemSelected: function (record, model, div, e) {  //define method of gridItemSelected function thats call on double click of grid row
        var address = Ext.ComponentQuery.query("#txtAreaAddress")[0];   //get component by its itemId and assign into address variable
        address.setValue(model.data.Address);   //get value by grid view model variable associate with data and dataIndex(Address) and set value into textfield
        var name = Ext.ComponentQuery.query("#txtName")[0];  //get component by its itemId and assign into name variable
        name.setValue(model.data.Name);  //get value by grid view model variable associate with data and dataIndex and set value into textfield
        var fatherName = Ext.ComponentQuery.query("#txtfatherName")[0];  //get component by its itemId and assign into fatherName variable
        fatherName.setValue(model.data.FatherName);  //get value by grid view model variable associate with data and dataIndex and set value into textfield
        var dob = Ext.ComponentQuery.query("#dtfield")[0];  //get component by its itemId and assign into dob variable
        dob.setValue(model.data.DOB);  //get value by grid view model variable associate with data and dataIndex and set value into textfield
        var contactNo = Ext.ComponentQuery.query("#nmbrFldContactNo")[0];  //get component by its itemId and assign into contactNo variable
        contactNo.setValue(model.data.ContactNo);  //get value by grid view model variable associate with data and dataIndex and set value into textfield
        var id = Ext.ComponentQuery.query("#ID")[0];  //get component by its itemId and assign into id variable
        id.setValue(model.data.ID);  //get value by grid view model variable associate with data and dataIndex and set value into textfield
        //var grid = Ext.ComponentQuery.query("#userGrid")[0];
        //grid.setVisible(false);
        //var popWindow = Ext.ComponentQuery.query('#popWindow')[0];
        //popWindow.hide();
        Ext.getCmp('popWindow').destroy();  //get popup window by its id and destroy window when record selected
    },
    updateClick: function () {  //updateClick function call on update button click
        var form = Ext.getCmp('userForm');   //get component of userForm and assign value into form variable
        var values = form.getValues();  //call getValue function by association of form variable and assign into values variable
        Ext.Ajax.request({     //send Ajax request to MVC controller request
            url: './User/Update',   //give path of method define in MVC controller
            method: 'POST',     //use POST method 
            jsonData: values,   //send values in the form of jsonData
            success: function (response) {      //define success function
                var result = Ext.decode(response.responseText);
                if (result.success === true) {
                    Ext.Msg.show({
                        title: 'EMPLOYEE',
                        msg: result.message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.MessageBox.INFORMATION
                    });
                }
                else {
                    Ext.Msg.show({
                        title: 'EMPLOYEE',
                        msg: result.message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.MessageBox.ERROR
                    });
                }
            },
            failure: function () {    //define failure function on response of mvc controller
                Ext.Msg.show({
                    title: 'Record not Updated',
                    msg: result.message,
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
            }
        });
    },
    deleteClick: function () {    //define deleteClick function on delete button click
        var form = Ext.getCmp('userForm');
        var values = form.getValues();
        Ext.Ajax.request({
            url: './User/Delete',
            method: 'POST',
            jsonData: values,
            success: function (response) {
                var result = Ext.decode(response.responseText);
                if (result.success === true) {
                    Ext.Msg.show({
                        title: 'Response if success true',
                        msg: result.message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.MessageBox.INFORMATION
                    });
                }
                else {
                    Ext.Msg.show({
                        title: 'Response if success false',
                        msg: result.message,
                        buttons: Ext.Msg.OK,
                        icon: Ext.MessageBox.ERROR
                    });
                }
            },
            failure: function () {
                Ext.Msg.show({
                    title: 'Record not deleted',
                    msg: result.message,
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
            }
        });
    }
});
Code of MVC controller thats interact with database and perform Save,Delete
and Update operation according to user need.
using _20012017.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
namespace _20012017.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/
        static string message = string.Empty;   //define string type static variable 
        static bool success = false;   //define bool type static variable
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Save(Employee model) //define Save function thats call from controller.Its return type is JsonResult 
        {
            try    //all statement written in try block thats may be causes abnormal conditions(exception)
            {
                using (harsh_dbEntities db = new harsh_dbEntities()) //harsh_dbEntities is object thats add on ADO.NET Entity Data Model
                {
                    db.EmployeeMaster.Add(new EmployeeMaster  //EmployeeMaster is table name in database and Add function call for store data into database
                    {
                        Address = model.Address,  //store data into database table column Address
                        ContactNo = model.PhoneNo,  //store data into database table column ContactNo
                        DOB = model.DOB,   //store data into database table column DOB
                        FatherName = model.FatherName,   //store data into database table column FatherName
                        Name = model.Name   //store data into database table column Name
                    });
                    db.SaveChanges();  //call function SaveChanges() associated with database object db for save change into database
                    success = true;
                    message = "Record saved successfully";
                }
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }
            return Json(  //return response in the form of Json
                new
                {
                    success,
                    message
                }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult Show()  //define Show function 
        {
            try
            {
                using (harsh_dbEntities db = new harsh_dbEntities())//harsh_dbEntities is object thats add on ADO.NET Entity Data Model
                {
                    var data = db.EmployeeMaster.ToList();  //get all data from database and assign in data variable
                    success = true;
                    return Json(
                                new
                                {
                                    data,
                                    success
                                }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
                return Json(
                                new
                                {
                                    success,
                                    message
                                }, JsonRequestBehavior.AllowGet);
            }
        }
        [HttpPost]
        public JsonResult Update(Employee model)
        {
            try
            {
                using (harsh_dbEntities db = new harsh_dbEntities())
                {
                    //int id = Convert.ToInt32(model.ID);
                    var data = db.EmployeeMaster.FirstOrDefault(x => x.ID == model.ID);  //FirstOrDefault function to select single record for get ID and check its equal to id return 
                    data.Name = model.Name;  //update data into database column Name
                    data.ContactNo = model.PhoneNo;   //update data into database column ContactNo
                    data.FatherName = model.FatherName;   //update data into database column Address
                    data.Address = model.Address;  //update data into database column Address
                    data.DOB = model.DOB;   //update data into database column DOB
                    //db.EmployeeMaster.Attach(data);
                    db.SaveChanges();  //call SaveChanges() function
                    success = true;
                    message = "Record updated successfully";
                }
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }
            return Json(
                new
                {
                    success,
                    message
                }, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult Delete(Employee model)
        {
            try
            {
                using (harsh_dbEntities dbs = new harsh_dbEntities())
                {
                    var data = dbs.EmployeeMaster.Where(a => a.ID == model.ID).FirstOrDefault();//when we select multiple record then write .ToList() instead of FirstOrDefault() 
                    if (data != null)  //check condition if data is not null false 
                    {
                        dbs.EmployeeMaster.Remove(data);  //delete record in database,call Remove function and pass object of selected column
                        dbs.SaveChanges();  //call SaveChanges() function
                        success = true;
                        message = "Record deleted successfully";
                    }
                    else
                    {
                        success = false;
                        message = "Please select record on grid";
                    }
                }
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }
            return Json(  //return Json data
                new
                {
                    success,
                    message
                }, JsonRequestBehavior.AllowGet);
        }
    }
}
Code of MVC model thats defined all fields datatypes and give advantage of
perform multiple operations with single parameters.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace _20012017.Models
{
    public class Employee
    {
        public Int32 ID { get; set; }
        public string Name { get; set; }
        public string FatherName { get; set; }
        public DateTime DOB { get; set; }
        public string Address { get; set; }
        public string PhoneNo { get; set; }
    }
}

Updated 07-Sep-2019
Exploring the online world is my passion. have experience of #content writing #SEO #Digital Marketing #On-Page #Lead Generation #Content Analyst #Marketing Analyst... I could never stop at one point, continuously wanted to acquire more and more skills. My work for any organization will be full of passion and hard work.

Leave Comment

Comments

Liked By