Adding a checkbox in a GridPanel


Since you are trying to add a checkbox (probably in the beginning of the grid itself) in a GridPanel, it is obvious that you want to use a custom selection model, CheckboxSelectionModel. By looking at GridPanel’s API you quickly realize that you need to set value of selModel with an instance of CheckboxSelectionModel. So, you write following code:

var checkBoxSelMod = new Ext.grid.CheckboxSelectionModel();
var manageDoctorGrid = new Ext.grid.GridPanel({
frame:false,
autoHeight:true,
height : 'auto',
width:500,
selModel : checkBoxSelMod,
store: doctorSearchResultStore,
columns: [
{header: " Doctor Name ", dataIndex: 'doctor_name', width: 249 },
{header: " Hospital Name ", dataIndex: 'hospital_name', width: 249 }
]
});

Once you launch your application, you realize that nothing happened. This is where lack of ExtJS documentation hurts you. It never explicitly talks about defining a column, in the column list, which has a value of selection model object. Following piece of code works just alright:

var checkBoxSelMod = new Ext.grid.CheckboxSelectionModel();
var manageDoctorGrid = new Ext.grid.GridPanel({
frame:false,
autoHeight:true,
height : 'auto',
width:500,
selModel : checkBoxSelMod,
store: doctorSearchResultStore,
columns: [
checkBoxSelMod,
{header: " Doctor Name ", dataIndex: 'doctor_name', width: 249 },
{header: " Hospital Name ", dataIndex: 'hospital_name', width: 249 }
]
});

Above code adds a check box in the beginning of every row. You can switch position of check box by placing the selection model object at desired position in the column list. For example, if you want to see checkbox in the middle of doctor name and hospital name then place the object between these two columns.

Tagged with: ,
Posted in Sencha ExtJS
22 comments on “Adding a checkbox in a GridPanel
  1. UDU says:

    How to do this dynamically

  2. Sumit Jain says:

    Hi,

    When i use below code in one view initcomponent function for inserting checkbox in columns, i get error –> “Uncaught TypeError: undefined is not a function ” at
    –> var checkBoxSelMod = new Ext.grid.CheckboxSelectionModel();
    means it is not recognising checkboxselectionmodel …
    —————————-
    var checkBoxSelMod = new Ext.grid.CheckboxSelectionModel();
    var manageDoctorGrid = new Ext.grid.GridPanel({
    frame:false,
    autoHeight:true,
    height : ‘auto’,
    width:500,
    selModel : checkBoxSelMod,
    //store: doctorSearchResultStore,
    columns: [
    checkBoxSelMod,
    checkBoxSelMod,
    checkBoxSelMod
    ]
    });
    —————————————
    ————————————-My view code is given below——————-
    Ext.define(‘AM.view.user.PermissionGrid’, {
    extend:’Ext.grid.Panel’,
    alias:’widget.permissionGrid’,
    title:’Permission Grid’,

    initComponent: function() {
    var checkBoxSelMod = new Ext.grid.CheckboxSelectionModel();
    var manageDoctorGrid = new Ext.grid.GridPanel({
    frame:false,
    autoHeight:true,
    height : ‘auto’,
    width:500,
    selModel : checkBoxSelMod,
    //store: ‘PermissionGrid’,
    columns: [
    checkBoxSelMod,
    checkBoxSelMod,
    checkBoxSelMod
    ]
    });

    this.callParent(arguments);

    }
    });

    Please suggest

  3. Sumit Jain says:

    Hi,

    When i use below code in one view initcomponent function for inserting checkbox in columns, i get error –> “Uncaught TypeError: undefined is not a function ” at
    –> var checkBoxSelMod = new Ext.grid.CheckboxSelectionModel();
    means it is not recognising checkboxselectionmodel … 😦
    —————————-
    var checkBoxSelMod = new Ext.grid.CheckboxSelectionModel();
    var manageDoctorGrid = new Ext.grid.GridPanel({
    frame:false,
    autoHeight:true,
    height : ‘auto’,
    width:500,
    selModel : checkBoxSelMod,
    //store: doctorSearchResultStore,
    columns: [
    checkBoxSelMod,
    {header: ” Doctor Name “, dataIndex: ‘doctor_name’, width: 249 },
    {header: ” Hospital Name “, dataIndex: ‘hospital_name’, width: 249 }
    ]
    });
    —————————————
    ————————————-My view code is given below——————-
    Ext.define(‘AM.view.user.PermissionGrid’, {
    extend:’Ext.grid.Panel’,
    alias:’widget.permissionGrid’,
    title:’Permission Grid’,

    initComponent: function() {
    var checkBoxSelMod = new Ext.grid.CheckboxSelectionModel();
    var manageDoctorGrid = new Ext.grid.GridPanel({
    frame:false,
    autoHeight:true,
    height : ‘auto’,
    width:500,
    selModel : checkBoxSelMod,
    //store: ‘PermissionGrid’,
    columns: [
    checkBoxSelMod,
    checkBoxSelMod,
    checkBoxSelMod
    ]
    });

    this.callParent(arguments);

    }
    });

    Please suggest

  4. manojparida says:

    Hello,
    While i creating Template for Group Header with using DataView,in my store all data exits,i need one Group header template by which i can see a group header as well as elements,i added this template in a Panel which has unique height(300) and elements are displaying according to height in two columns and shall no scrolling,but all data are not displayed as scroll property is restricted and second column is not shown.
    i written below code,for this give some needful suggestion.

    var wtTemplate = new Ext.XTemplate(
    ”,
    ”,
    ‘{group} ( Country )’,
    ”,
    ”,
    ‘ {States} />’,
    ”,
    ”,
    ”,
    ”,

    );

    var myPanel = new Ext.Panel({
    id: ‘manPanel’,
    title: ‘My Template with Group Header ‘,
    //autoScroll: true,
    items: new Ext.DataView({
    itemSelector: ‘div.dataview-item’,
    overClass: ‘dataview-item-over’,
    store: myDataStore,
    tpl: wtTemplate,
    listeners: ({
    ‘click’: function(dataview, nodeindex, node, evt) {
    Ext.Msg.alert(” My Template”,”Template with Group Header t”);
    }

    })
    })
    });

    {States} values is dispalyed in one column and few data is missing which meant for second column.

  5. Manoj Parida says:

    Thanks.

  6. Walking Tree says:

    Manoj,

    I don’t think accessing the individual checkboxes in classBPanel to register the handler for their ‘check’ event is a good idea. Rather, you shall fire custom events based on which check box has been clicked and then relay those custom events in classAPanel. That way you would be able to take specific action corresponding to the checkbox that has been clicked.

    Hope this helps!

    Cheers

  7. Manoj Parida says:

    These all relayEvents should be registered in classBPanel.js for all different objects individually,then output will diiferent for each ckecked and unchecked,we have to write this code

    classBPanel.js
    ——————-
    this.classAPanel.checkbxA.on(‘check’, function(thisCbx,checked){
    Ext.Msg.alert(” Multiple Checkbox”,”CheckboxA is clicked”);
    });

    this.classAPanel.checkbxB.on(‘check’, function(thisCbx,checked){
    Ext.Msg.alert(” Multiple Checkbox”,”CheckboxB is clicked”);
    });

    this.classAPanel.checkbxC.on(‘check’, function(thisCbx,checked){
    Ext.Msg.alert(” Multiple Checkbox”,”CheckboxC is clicked”);
    });

  8. Manoj Parida says:

    I have one panel, in which there is three Checkbox placed,i have to check and unCheck three Checkbox with different functionality for check ,so i use relayEvents in subclass and this event(check) is registered in parent class and these are apply in xtype:FieldSet in same panel,but the problem is,output is same for all Checkbox i;e same Msg is Popuped for all three Checkbox when checked,so how to divide three check in classBPanel.js, see the code given below

    classAPanel.js
    ————–
    this.relayEvents(checkbxA, [‘check’]);
    this.relayEvents(checkbxB, [‘check’]);
    this.relayEvents(checkbxC, [‘check’]);

    classBPanel.js
    ————–

    this.classAPanel.on(‘check’, function(thisCbx,checked){
    Ext.Msg.alert(” Multiple Checkbox”,”All check event will have different functionality”);
    });

  9. Manoj Parida says:

    Thanks for this features in Grid.

  10. top_1 says:

    i have a problem when using checkbox model with paging..
    ex., at first page…i check 3 items.,then i go to page 2…and check 2 items. Now.,i’m back to page 1..all items back to normal…no items is being checked…
    can you help my problem ?

    thx.,

  11. seltzlab says:

    I’ve tried to setup a grid with an Id header and a CheckboxSelectionModel: it seems that together does not work! Maybe a bug?

  12. wtcindia says:

    I want the row to be selected only when I click on the checkbox

    By default, when you click on the any cell of a grid, the complete row is selected and also the checkbox is checked. Now, if you want the row to be selected only when the checkbox is clicked, you can use the checkOnly config property of CheckboxSelectionModel. Setting checkOnly to true will ensure that the row is selected when you click on the checkbox.

  13. wtcindia says:

    Adding tool bar and paging bar
    Adding tool bar and paging bar into a grid is very common. For example, most of the manage window in our HCIS product uses following design:
    1) Search Criteria
    2) Search Result displayed in grid with toolbar and paging bar (optional)

    Tool bar usually consists of operations like add, remove, edit and view, while paging allows you to view the sub-set of results at a time.

    What do you need to do to be able to add tool bar and paging bar?

    Create appropriate instance of Ext.PagingToolbar and Ext.Toolbar.Button. The code snippet would look like:

    bbar:pagingBar,
    tbar:[
    addBtn,
    editBtn,
    viewBtn,
    deleteBtn
    ]

    A completely working pagingBar would look like as follows:

    var pagingBar = new Ext.PagingToolbar({
    pageSize: 10,
    store: patientMgmntDataStore,
    displayInfo: true,
    displayMsg: 'Displaying records {0} - {1} of {2}',
    emptyMsg: "No registrations to display",
    onClick : function(which){
    switch(which){
    case "first":
    patientMgmntDataStore.reload({params:{start: 0, limit: this.pageSize}});
    break;
    case "prev":
    patientMgmntDataStore.reload({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
    break;
    case "next":
    patientMgmntDataStore.reload({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
    break;
    case "last":
    var total = patientMgmntDataStore.getTotalCount();
    var extra = total % this.pageSize;
    var lastStart = extra ? (total - extra) : total-this.pageSize;
    patientMgmntDataStore.reload({params:{start: lastStart, limit: this.pageSize}});
    break;
    case "refresh":
    patientMgmntDataStore.reload({params:{start: this.cursor,limit:this.pageSize,myparams:'val'}});
    break;
    }
    }
    });

    It is very important to ensure that you send correct value of start and limit to the backend for retrieving the records. Also, ensure that you really use the limit and start in forming your SQL query. If you are using MySQL in the backend then it even provides you a key word, [LIMIT {[offset,] row_count | row_count OFFSET offset}], where start will act as an offset value and limit will act as a row count.

    Instantiating button is even easier. For example, to create an instance for addBtn, only significant thing you will have to do is to create handler function for the button:
    var addBtn = new Ext.Toolbar.Button({
    cls:'x-btn-text-icon',
    text:msg.add,
    icon:'images/add.png',
    handler: function(){
    handlePatientMgmntNewPatientBtn();
    }
    });

    Hope you find this useful.

    • Sula says:

      The code inside

      var pagingBar = new Ext.PagingToolbar({
      …..
      });

      to handle the first, next, previous and last button clicks looks something which might not be required. If the method, which is called to load the store data, provides the correct value of “totalCount” property, then, ExtJS paging bar is expected to do the calculation of the start and limit property values based on it and hence the caller shall not be required to have the calculation done in their code. I have been using PHP in the back-end and didn’t have to carry out the calculation.

      • wtcindia says:

        Sula,
        JsonStore is pre-configured with a built-in Ext.data.JsonReader, which has a configuration option, totalProperty. The definition of this config option says:
        totalProperty
        Name of the property from which to retrieve the total number of records in the dataset. This is only needed if the whole dataset is not passed in one go, but is being paged from the remote server.

        I think, the moment, we set this value, ExtJS assumes that you intend to page data from remote server and hence, we may not require separate code for handling prev, next, first, last etc.

        In any case, we must ensure that you send the correct number of totalCount, matching the select criteria of the user.

        Thanks for your input.

    • wtcindia says:

      Another very frequent need is of refreshing the grid after performing operations like add, edit and delete.

      If you have used Ext.data.JsonStore to store the remotely-loaded JSON data then it is really easy. All you need to do is to call reload on your data store.
      patientMgmntDataStore.reload({params:{start: this.cursor,limit:this.pageSize,myparams:’val’}});

  14. wtcindia says:

    What do you do if you want to allow selection of at most one checkbox at a time?
    It is very straight forward in ExtJS. Ext.grid.RowSelectionModel provides a config option, singleSelect (default false). Since, CheckboxSelectionModel is subclass of RowSelectionModel, by setting singleSelect to true, you can force selection of zero or one checkbox from the grid.

  15. wtcindia says:

    Writing listener for CheckboxSelectionModel
    There may be cases where you need to write listeners to be able to perform tasks dependent on the checkbox selection. Specially when you intend to view, edit or delete the selected entry ( or entries in case of delete) from the grid, you do need to define a suitable listener. The obvious question is, where do you define that listener and what all events you may be interested in?

    You define your listener on CheckboxSelectionModel. The most frequently used public events are rowdeselect (fires when a row is deselected) and rowselect (fires when a row is selected). Both the events provides you three arguments:
    1. SelectionModel
    2. rowIndex
    3. Record

    SelectionModel’s getSelections provides you the list of selected nodes at any moment, which you can use to implement your business logic. Following code explains how to do that:

    var checkBoxSelMod = new Ext.grid.CheckboxSelectionModel( {
    listeners:{
    rowselect : function( selectionModel, rowIndex, record){
    var selectedRows = selectionModel.getSelections();
    if( selectedRows.length > 0){
    for( var i = 0; i 0){
    for( var i = 0; i < selectedRows.length; i++) {
    ; // Do whatever you want to do
    }
    }
    // More code related to deselection of a chekbox
    }
    }
    });

  16. wtcindia says:

    Grid panel provides three ways to specify the columns of the grid:
    columns attribute, which is an array of columns to auto create a ColumnModel
    colModel attribute, which takes an instance of Ext.grid.ColumnModel to use when rendering the grid and
    cm which is a short hand of colModel.

    While cm and colModel are same, you may wonder why you need 3rd one, columns?

    Well, the answer lies in whether you want to create explicitly or you want to let ExtJS decide about when to create the object. Later case is usually recommended.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

We Have Moved Our Blog!

We have moved our blog to our company site. Check out https://walkingtree.tech/index.php/blog for all latest blogs.

Sencha Select Partner Sencha Training Partner
Xamarin Authorized Partner
Do More. With Sencha.

Recent Publication
%d bloggers like this: