articles

Home / DeveloperSection / Articles / Crud Operation in Border Layout on Grid

Crud Operation in Border Layout on Grid

Hemant Patel 2887 17-Feb-2017


In this UI we use border layout and inject User form in main view in the center. And in the bottom we use a Grid that shows record of the database. When we click on grid row, then related data bind to text fields. All Crud operation like to, save, delete and update can allow to the user. All changes can perform in the database.

Crud Operation in Border Layout on Grid

Code of HTML page
<!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> 
</head>
<body>
</body>
</html>

Code of border layout
Ext.define('app.view.Notepad',  
    {
        extend: 'Ext.panel.Panel',   //Extend Panel class
        alias: 'widget.Notepad',  // define alias
        title: 'UI Testing', 
        xtype: 'layout-border',
        requires: ['Ext.layout.container.Border', 'app.view.UserFormView', 'app.view.UserGridView'],
        layout: {
            type: 'border',
            align: 'center'
        },
        margin: '10 0 0 280',
        width: 800,
        height: 600,
        bodyBorder: false,
        defaults: {
            collapsible: true,
            split: true,
            bodyPadding: 10
        },
        initComponent: function () {
            Ext.apply(this, {
                items: [
                   {
                       xtype: 'userFormView',
                       title: 'Main Content',
                       collapsible: false,
                       region: 'center',
                               autoScroll: true
                           },
                    {
                        xtype: 'userGridView',
                               reference: 'userGridFooter',
                        itemId: 'userGridFooter',
                        id: 'userGridFooter',
                        region: 'south',
                        height: 200,
                        minHeight: 75,
                        maxHeight: 250,
                    },
                    {
                        title: 'Navigation',
                        region: 'west',
                        floatable: false,
                        margin: '5 0 0 0',
                        width: 5,
                        minWidth: 100,
                        maxWidth: 250,
                    },
                ]
            });
            this.callParent(arguments);
        }
    });
Code of User Form
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
    alias: 'widget.userFormView',//define alias for direct accessing in other form
    border: true,
    id: 'userForm',
    title: 'User Form',
    titleAlign: 'center',
    cls: 'my-fieldset',
    height: 350,
    controller: 'tabController',
    layout: {
        type: 'vbox',
        pack: 'center'
    },
    fieldDefaults: {
        xtype: 'textfield',
        xtype: 'textarea',
        xtype: 'trigger',
        labelAlign: 'top',
        labelStyle: 'font-weight:bold;color:#00baff',
        width: '95%'
    },
    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',
        maxLength: 8,
        enforceMaxLength: true,
        maskRe: /[a-zA-Z]/,//another way to define validation
        style: 'text-align:left',
        margin: '5 0 0 10',
        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',
        maxLength: 8,
        enforceMaxLength: true,
        maskRe: /[^@#$%&*0-9^]/,  //validation tool for  write only alphabets in textfield
        margin: '0 0 0 10',
        itemId: 'txtfatherName',
    },
    {
        xtype: 'datefield',
        fieldLabel: 'D.O.B',
        name: 'DOB',
        maskRe: /[]/, //validation tool for  select only datefield
        maxLength: 10,
        enforceMaxLength: true,
        margin: '0 0 0 10',
        itemId: 'dtfield'
    },
    {
        xtype: 'textarea',
        fieldLabel: 'Address',
        name: 'Address',
        itemId: 'txtAreaAddress',
        maxLength: 200,
        enforceMaxLength: true,
        margin: '0 0 0 10',
        reference: 'txtAreaAddress'
    },
    {
        xtype: 'textfield',
        fieldLabel: 'Contact No.',
        name: 'PhoneNo',
        maskRe: /[^a-zA-Z!@#$%^&*()_+=-~^]/, //validation tool for insert only numeric data in textfield
        maxLength: 12,
        enforceMaxLength: true,
        margin: '0 0 10 10',
        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%',
        items: [
        {
            xtype: 'button',
            text: 'Submit',
            width: '25%',
            padding: 5,
            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',
            padding: 5,
            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',
            padding: 5,
            text: 'Update',
            listeners: //implement listener for call function of controller
            {
                click: 'updateClick', //call method of controller on button click
            }
        }
        ]
    }
    ]
});
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: 200,
    autoLoad: true,
            store: Ext.create('app.store.TabStore'),  //use store by given its path
            columns: [
            {
                xtype:'rownumberer'
            },
            {
                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'
            }
       });
Code of Popup window that's call on browser click 
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 app.js file for render all pages with database
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 model tabModel.js
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 contoller tabController.js
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
        Ext.getCmp('popWindow').destroy();  //get popup window by its id and destroy window when record selected
    },

    updateClick: function (field, newValue, oldValue) {  //updateClick function call on update button click
        console.log(field);
        var me = this;
        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) {
                    window.location.reload();
                        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 Store tabStore.js
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 MVC controller for interact with database
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())
                {
                   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.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);
        }
    }
}

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