donderdag 4 maart 2010

ExtJS editor grid server side example

Hi,

this is my first post and i want to show some examples about usage of ExtJS grid together with a server-side language like PHP or Ruby.

Editor grid contains three main components.

  1. Data store: this store loads the records being inserted in ExtJS grid. This component is an instance of Ext.data.Store (You can use Grouppingstore as well)
  2. Editor Grid: this component shows the records in a grid view. This is an instance of Ext.grid.EditorGridPanel. the difference between a regular grid and an editor grid is, you can specify the xtype of the editor for each column. This editor will fire afteredit event which is only available for an EditorGridPanel instance. There are also few other EditorGridPanel specific events like beforeedit, onchange, etc.
  3. Server-side class, function, file whatever you like. My example will be a PHP example but the main logic is same for the other languages. First function will receive the post data, change the value in database according to the key that is sent. and return a JSON object as response which contains the parameter success {"success":true} or false and second function will send the data so store can reload itself and update the involved grid.
first create the table employers (well i am not going to write the query here):
employers:
id: primary key
name: string
surname: string
address: string

Our class will contain two functions

class EditorGridListener{
/*i assume you have a kind of db class that can handle the queries so this is just a pseudo class, this methods should b defined and included before use. So don't ask me why you get method doesn't exist error.*/
private $yourDbClass;

//we simply create the instance with the $_POST array as parameter
public function __construct($post){
//define the db handler
$this->yourDbClass = new YourDatabaseClass;
//run the function requested and print the result
switch($post["task"]){
case "load":
//if $_POST["task"] equals load run this function
print $this->loadGrid();
break;
case "edit":
//if $_POST["edit"] equals load run this function
print $this->editValue($post["id"], $post["key"], $post["value"]);
break;
}
}
private function loadGrid(){
//we simply take all records and send them to the extjs grid as json object
$records = $this->yourDbClass->toArray("employers");
return json_encode(Array("success"=>true, "root"=>$records));
}
private function editValue($id, $key, $value){
//we update the table and change the $key's value to $value for the row $id
$success = $this->yourDbClass->exec("UPDATE employers SET " . $key . "='" . $value . "' WHERE id=" . $id);
return json_encode(Array("success"=>$success));
}
}

$lstnr = new EditorGridListener($_POST);

Now second part, creating the store:

var employerStore = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
//this is where you send the variables and get a response
url: "your-server-side-code.php"
}),
baseParams:{
/*this parameters will be sent with the request. You can add more values like date: new Date(); to load records belong to specific date*/
task: "load"
},
//reader will decode the response.
reader: new Ext.data.JsonReader({
//we put the records in "root" value of the response json which is an array
root: "root"
}, [{
//you have to map at least one column
name: "id",
mapping: "id"
}, "name", "surname", "address"]
)
});

Now we are creating the editor grid:


var = new Ext.grid.EditorGridPanel({
//we bind employerStore with this grid. so if you reload the store, the grid will be updated too
//this is one of the features of ExtJS i like
ds: employerStore,
//some layout values
autoScroll: true,
autoWidth: true,
height: 290,
//it will start editing after 1 click, default is 2
clicksToEdit: 1,
margins: "0 5 5 5",
//we define here the columns retrieved from the data store
columns:[
/*as you see, each column has it's own editor value so you can use any form element as editor including checkbox. once the user clicks on single cell, it will turn into what is described in the editor property of column with it's value*/
{header: "Name", dataIndex: "name", width: 0.2, editor: new Ext.form.TextField({})},
{header: "Name", dataIndex: "surname", width: 0.2, editor: new Ext.form.TextField({})},
{header: "Name", dataIndex: "address", width: 0.6, editor: new Ext.form.TextField({})}
],
listeners: {
//this will fire when the editing is done and the cell lost the focus
afteredit: function(event){
//event is an object and contains all values we need
Ext.Ajax.request({
//your serverside script. refer the php code above
url: "your-server-side-code.php",
//they are other parameters to call editValue function
params: {
task: "edit",
key: event.field,
value: event.value,
id: event.record.data.id
}
/*every ajax request has two callbacks as usual, success callback and error callback. if the response contains a JSON object and the key success equals to true, this function will be called, and if the value is false, failure function will be called*/
success: function(){
//just reload the store to sync with the actual mysql table
event.grid.store.reload();
},
failure: function(){
/*show an error if anything goes wrong.*/
Ext.Msg.alert("Error", "Something went wrong");
}
});
}
}
});

I hope someone can use this information to build powerfull desktop-like web applications with ExtJS. See you soon.

1 opmerking:

  1. If you had a code plugin in your blog would be more readable!

    BeantwoordenVerwijderen