Zend Framework

Archive for January 12th, 2009

Zend Framework and dojo-grid sorting example

Posted by Faheem Abbas on January 12, 2009

In my previous post “dojo-grid-in-zend-framework:creating-nice-and-cool-grid-in-php-using-zend-framework-and-dojo” I discuss how to creat nice and cool gird using Zend framework and dojo.

In this article I am going one step further and show you how easy it is to apply sorting to your dojo grid.

Please read my previous article befor writing this code.

In your model write

public function getJobsData($sort,$order)

{

$select = $this->_db->select()

->from($this->_name)

->order(” “.$sort.” ” . $order);

$results = $this->getAdapter()->fetchAll($select);

return $results;

}

If you compare this model with the previous one, you will find that we are passing tow extra parameter here and a line

->order(” “.$sort.” ” . $order);

This will sort our data according to the field we will click on.

Now In your controller, write

public function  recordsAction()

{

$jobs = new Jobs();

if ($this->getRequest()->isXmlHttpRequest()){

$sort=$this->getRequest()->getParam(’sort’);

}

if($sort==”"){

$sort=”id”;

}

if(strchr($sort,’-')){

$sort = substr($sort,1,strlen($sort));

$order = “Desc”;

} else {

$order=”Asc”;

}

$data= $jobs->getJobsData($sort,$order);

$dojoData= new Zend_Dojo_Data(‘id’,$data,’id’);

echo $dojoData->toJson();

exit;

}

Here we first check if we get ajax request. If yes, we get the value of the variable sort (dojo grid passed this as parameter when we click on it field), so we should not worry about it. Dojo grid either pass “field name” or field name with -ve sign.

we check if the sort variable has -ve sign attached with it. If we found we then remove the first character and set sort order to “Desc”. if we don’t find -ve sign we simply set sort order to “Asc”. we then call our model function

getJobsData() giving it $sort and $order variable. the result return is converted to json.

The last minor change we will do in our view template code

<div dojoType=”dojox.data.QueryReadStore” clientSort=”true jsId=”activeStore”, url=”records” ></div>

The only change we did is highlited in red.

That’s it nice and cool dojo grid with sorting.

Hopefully in next article I’d discuss how to implement pagging in the dojo grid.

Posted in Zend Framework | 3 Comments »