Grid Extjs: Checkbox Selection

this section, i want to share about using Checkbox Selection on Grid Extjs, here i have used Checkbox Selection to editing and deleting file from grid. I got this tutorial from www.extjs.com, then I combine with php to manipulate database data, such as editing and deleting files. Plugin which used here was checkbox selection.

The most important  script in this tutorial is as follow

var Checkbox = new Ext.grid.CheckboxSelectionModel();

Below is the screen shot of this tutorial, you can editing  file if you have selected a checkbox. and you can also deleting file if you have selected one or more checkbox.

check-box-grid-extjs

And following some of the files needed to making “Grid Extjs: Checkbox Selection” tutorial.

Frist step is create a table on database, name’s table of this tutorial is simpleform. This table have more field are  id, name, address, and email. and primary key of this field is id.

CREATE TABLE IF NOT EXISTS `simpleform` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(50) NOT NULL,
`address` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;

--
-- Dumping data for table `simpleform`
--

INSERT INTO `simpleform` (`id`, `name`, `address`, `email`) VALUES
(1, 'faisal amir', 'jl Pamekasan 87', 'faisal@yahoo.com'),
(2, 'kahayan', 'blitar no 3', 'kahayan@yahoo.its'),
(3, 'abid', 'lumajang', 'abid@gmail.com'),
(4, 'Billy', 'lumajang', 'billy@gmail.com'),
(5, 'didik', 'pamekasan', 'didik@plasa.com'),
(6, 'kakase', 'saikato', 'kakase@yahoo.com'),
(7, 'yudik', 'sikio', 'yudik@gmail.com');

Second step is create a php file to connect to database, database is a important to runing this tutorial. name`s database of this tutorial is defafe.

Example: name of this file is koneksi.php

$nameserver = "localhost";
$username = "root";
$password = "";
$dbname = "defafe";
mysql_connect($nameserver,$username,$password)or die('error'.mysql_error());
mysql_select_db($dbname);
?>

Third step is Create html file to call or includ  javascript and css files.

Note The most important of this file is sequence of this file can not be replaced.

Below are the sequences of this file

1. include ext-all.css

2. include ext-base.js

3. include ext-all.js

4. include simplegrid.js

Example: name of this file is index.html





Next step is Create javascript file to make a form

Example: name of this file is simplegrid.js

Ext.onReady(function(){

Ext.QuickTips.init();

var Checkbox = new Ext.grid.CheckboxSelectionModel();//component chexbox

var SimpleDataStore = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: 'simplegrid.php',
method: 'POST'
}),
reader: new Ext.data.JsonReader({
root: 'results',
totalProperty: 'total'

},
[
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'address', type: 'string'},
{name: 'email', type: 'string'}

]),
sortInfo:{field: 'id', direction: "ASC"}
});

SimpleDataStore.load({params:{start:0,limit:6}});

var SimpleColumnModel = new Ext.grid.ColumnModel(
[
Checkbox,//call Checkbox
{
header: 'Id',
readOnly: true,
dataIndex: 'id',
width: 40,
hidden: false

},{
header: 'Name',
dataIndex: 'name',
width: 130

},{
header: 'Address',
dataIndex: 'address',
width: 200

},{
header: 'Email',
dataIndex: 'email',
vtype:'email',
width: 180
}]
);
SimpleColumnModel.defaultSortable= true;
var formEdit = new Ext.form.FormPanel({
url:'simplegrid.php?act=edit', //include simplegrid file and action is edit
baseCls: 'x-plain',
labelWidth: 90,
defaultType: 'textfield',
reader: new Ext.data.JsonReader ({
root: 'results',
totalProperty: 'total',
id: 'id',
fields: [
'id','name','address','email'
]
}),
items: [
new Ext.form.Hidden ({
name: 'id'
}),
{
fieldLabel: 'Name',
name: 'name',
anchor:'100%'
},
{
fieldLabel: 'Address',
name: 'address',
xtype:'textarea',
width:220
},
{
fieldLabel: 'Email',
name: 'email',
vtype:'email',
width:220
}
],

buttons: [{
text: 'SAVE',
handler:function(){
formEdit.getForm().submit({
waitMsg:'Storing Data...',
failure: function(form, action) {
Ext.MessageBox.alert('Error Message', 'Data Failur.....');
formEdit.getForm().reset();
},
success: function(form, action) {
Ext.MessageBox.alert('Confirm', 'Success to storing data...');
SimpleDataStore.load({params:{start:0,limit:6}});
window.hide();
formEdit.getForm().reset();
}
})
}
},{
text: 'Cancel',
handler: function(){
window.hide();
}
}]
});
var window = new Ext.Window({
title: 'Edit Input',
width: 340,
height:310,
minWidth: 300,
minHeight: 310,
layout: 'card',
plain:true,
bodyStyle:'padding:3px;',
buttonAlign:'center',
closeAction:'hide',
modal: true,
animCollapse:true,
activeItem:0,
items: [
formEdit
]
});
//function delete
function del(btn){
if(btn == 'yes'){
var m = SimpleListingEditorGrid.getSelections();
SimpleDataStore.load({params:{del:m[0].get("id"),start:0,limit:6}});
}
}

var SimpleListingEditorGrid =  new Ext.grid.GridPanel({
title: 'Simple Grid',
store: SimpleDataStore,
cm: SimpleColumnModel,
sm: Checkbox,
//componen tbar
tbar:[
{
//button edit
text:'Edit',
iconCls:'edit-grid',//create icon
handler: function()
{
var m = SimpleListingEditorGrid.getSelections();//function select
if(m.length > 0)
{
//get id
formEdit.getForm().load({url:'simplegrid.php?act=get&id='+ m[0].get('id'), waitMsg:'Loading'});
window.show();
}
else
{
Ext.MessageBox.alert('Message', 'please... Choose one of file...!');
}

}

},
{
//buttton delete
text:'Delete',
iconCls:'delete',//create icon
handler: function()
{
var m = SimpleListingEditorGrid.getSelections();
if(m.length > 0){
Ext.MessageBox.confirm('Message', 'are you sure to delete this file?' , del);
}
else{
Ext.MessageBox.alert('Message', 'please... Choose one of file...!');
}
}

}

],
viewConfig: {
forceFit:true
},

frame:true,
collapsible: true,
animCollapse: true,
width:480,
height:250,

bbar: new Ext.PagingToolbar({
pageSize: 6,
store: SimpleDataStore,
displayInfo: true,
displayMsg: 'Displaying data {0} - {1} of {2}',
emptyMsg: "No data to display"
})

});

SimpleListingEditorGrid.render('form');

});

Final step is Create php file to process data to the database

Example: name of this file is simplegrid.php

include "koneksi.php";
include "JSON.php";

if($_GET["act"] == "get"){//get id
$sql = "select * from simpleform where id = '".$_GET["id"]."'"; // choose id
$result = mysql_query($sql);
$rows = mysql_num_rows($result);
$arr = array();
while($obj = mysql_fetch_object($result))
{
$arr[] = $obj;
}
$jsonresult = JEncode($arr);
echo '({"total":"'.$nbrows.'","results":'.$jsonresult.'})';
}

else if($_GET["act"] == "edit"){
$sql = "update simpleform set name = '".$_POST["name"]."',address='".$_POST["address"]."', email='".$_POST["email"]."' where id='".$_POST["id"]."'"; //update data
mysql_query($sql) or die(mysql_error());
echo "{success:true}";
}

else if(isset($_POST["del"])){
$sql = "delete from simpleform where id ='".$_POST["del"]."'"; //delete data
mysql_query($sql) or die(mysql_error());
mysql_close();
}
else
{ $query = "SELECT * FROM simpleform"; //requset all data from simpleform
$result = mysql_query($query);
$nbrows = mysql_num_rows($result);
$start = (integer) (isset($_POST['start']) ? $_POST['start'] : $_GET['start']);
$end = (integer) (isset($_POST['limit']) ? $_POST['limit'] : $_GET['limit']);
$limit = $query." limit ".$start.",".$end;
//echo $limit;
$result = mysql_query($limit);

if($nbrows>0)
{
while($rec = mysql_fetch_array($result))    {

$arr[] = $rec;
}
$jsonresult = JEncode($arr);
echo '({"total":"'.$nbrows.'","results":'.$jsonresult.'})';
}
else
{
echo '({"total":"0", "results":""})';
}

}
// Encodes a SQL array into a JSON formated string
function JEncode($arr){
if (version_compare(PHP_VERSION,"5.2","<"))
{
require_once("JSON.php"); //if php<5.2 need JSON class
$json = new Services_JSON();//instantiate new json object
$data=$json->encode($arr);  //encode the data in json format
} else
{
$data = json_encode($arr);  //encode the data in json format
}
return $data;
}

?>

I hope you have enjoyed reading this tutorial.

Download   Source code

Tags: , , , , , , , , , , , , , , , , , , , , , , , ,

Incoming search terms for the article:

extjs grid checkbox , extjs checkbox , extjs checkbox in grid , extjs checkbox grid , extjs checkbox example , Ext grid CheckboxSelectionModel , ext grid checkbox , checkbox extjs , extjs grid checkbox column , extjs grid with checkbox , CHECKBOX GRID extjs , extjs editable grid , extjs form checkbox , extjs checkbox column , extjs checkboxselectionmodel example , ext checkbox , checkbox in extjs , extjs checkbox checked , ext js checkbox , checkbox extjs example , extjs grid checkboxes , editable grid extjs , check box selection exjs , grid extjs , extjs grid checkbox selection , checkbox in grid extjs , ext grid with checkbox , CheckboxSelectionModel disable checkbox , checkboxselectionmodel extjs , chexk box selection extjs defafe , ext grid columnmodel example , extjs grid delete checkbox , extjs CheckboxSelectionModel , extjs grid selection model , extjs gridpanel checkbox , checkboxselectionmodel example , how to reset checkbox in Extjs , extjs checkbox on , ext gridpanel checkboxcolumn , ext add checkbox column to grid , exjs grid checkboxes , extjs checkbox icon , editing records from database extjs forms , extjs checkbox handler , ext js checked , ext js example grid row selected , extjs grouping grid checkbox , ext checkbox grid , extjs grid selected row , ext grid checkboxselectionmodel example extjs themes , extjs file upload , extjs theme , extjs upload , extjs upload file , extjs grid checkbox , extjs tutorial , extjs login , extjs grid paging , extjs login form extjs checkbox readonly , checkbox row extjs , upload image extjs mysql , extjs file upload tutoriel , tutoriel extjs , extJS checkbox datastore , FileUploadField extjs documentation , icon-user-delete extjs , getSelectionModel() getSelections(); , register extjs application 

11 Responses to “Grid Extjs: Checkbox Selection”

  1. Animal says:

    Just a heads up, the line:

    SimpleListingEditorGrid.getSelections();

    Is invalid. That method has been removed. To get selections, use the gri’s SelectionModel:

    SimpleListingEditorGrid.getSelectionModel().getSelections();

  2. van says:

    very good , thank you for share

  3. Richa Gupta says:

    Hi

    I wanted to know How Can I show the check box in the disabled mode?? Only the header one

    Regards
    Richa

  4. Frederick D. says:

    I am very much enjoying your tutorials. You have a very good writing style and obviously know a lot about ExtJS. Your posts are a good resource for me and the project I have.

    I would like to ask for your help. For my project I am using a PHP framework called CakePHP. ExtJS can be integrated with it very well, but I need help in merging your tutorial here with what I have to work with.

    To produce grids in CakePHP it is commons to use from-markup.js to automagically read the HTML that is created for the table(s) used in a project. To create a simple grid it is easy. Using one of your tutorials I have even added the standard paging toolbar.

    I seek your help to show me how to merge what you have done above with the automagic capabilities of /examples/grid/from-markup.js. Will you please help me? Thank you in advance. If you need any sample files I can provide them via e-mail.

  5. tokkaido says:

    Hi, thanks for the tut!!, but how I delete more than 1 row? even when I selected more rows only delete the first one. Thanks in advance.

  6. faisal says:

    sorry!!!!
    This tutorial can only delete one row. you have to do looping

  7. Robert says:

    excellent contribution, thank you very much,

    Robert
    Santiago
    Chile.

  8. Calv says:

    to delete all rows, you need to :

    -get the selection array.
    -encode it to json (Ext.encode(the array).
    -use the php json_decode to get the array back.
    -do some while row in array …. DELETE row from…

    You get the idea ?

  9. Calv says:

    From the extjs website : (thanks to mjlecomte):
    http://www.extjs.com/forum/showthread.php?t=18435

    ———————————————————————————————

    replace te del function with this in the javascript file:

    //function delete
    function del(btn){
    if(btn == ‘yes’){

    //returns array of selected rows ids only
    var selectedKeys = grid.selModel.selections.keys;

    //encode array into json
    var encoded_keys = Ext.encode(selectedKeys);

    SimpleDataStore.load({params:{del:encoded_keys,start:0,limit:6}});
    }
    }

    ———————————————————————————————-

    replace the php file part “else if(isset($_POST["del"])){“:

    ———————————————————————————–
    else if(isset($_POST["del"])){

    $arr = $_POST['del'];

    $selectedRows = json_decode(stripslashes($arr));

    //should validate and clean data prior to posting to the database
    foreach($selectedRows as $row_id)
    {
    $id = (integer) $row_id;
    $query = “DELETE FROM simpleform WHERE id = ‘”‘ .$id.”‘”;
    mysql_query($query);
    }

    mysql_close();
    }

    ———————————————————————————–

    Later

  10. Aqeel says:

    Hi,

    I have download your source code and follow all your told steps, include fiels but the grid is showing no edit and delte function working………… please tell me any more suggestion……..

    Regards

  11. faisal says:

    please check my next tutorial “Part 1: simple application of extjs using layout browser”, i think, that tutorial can help you

Leave a Reply

Security Code: