Fix Ajax/javascript Gridviews With Unique Action Ids

If you’ve ever tried combining gridviews on a single page using Ajax, you’ve probably encountered problems getting the IDs to match up.

I’ve found a good method to fix that, which involves explicitly setting the grid id to a string that uniquely identifies the controller/action/parameters that produced the model that the grid is based on. My implementation of this method is below. Hope you find this useful, and I would love to know if anyone has a better way of doing or thinking about this issue.




<?php

// In your controller.


/**

 * Returns the unique id of the current action.

 * The action id consists of the unique id of the controller, the id of the action,

 * and the values of the action parameters.

 * You should override [[CController::getActionParams()]] to only return the relevant parameters.

 * The id is MD5'd to ensure consistent length, uniqueness, and that all characters are valid HTML.

 * @return string

 * @see CController::getActionParams()

 * @see CController::getUniqueId()

 */

public function getUniqueActionId()

{

    return md5(implode('-', array(

        $this->getUniqueId(),

        $this->action->id,

    ) + $this->getActionParams()));

}


// In your view

$this->widget('bootstrap.widgets.TbGridView', array(

    'id' =>$this->getUniqueActionId(),

    'filter' =>$model,

    'dataProvider' =>$model->search(),

    'columns' =>$model->columns(),

    ...

));