Change buttons on our CGridView extending yii

In this tip, I'll help you to change in few second buttons of your CGridView. I hope you like it =).

This is our standard grid created by yii (with gii, or console, ...)

$this->widget('zii.widgets.grid.CGridView', array(
        'id' => 'standard-grid',
        'dataProvider' => $model->search(),
        'filter' => $model,
        'columns' => array(
            'id',
            'field',
            array(
                'class' => 'CButtonColumn',
            ),
        ),
    ));

What if we want to easy upgrade columns of all our grid? we can extend CButtonColumn with a new class. We can create this class and call it MyCButtonColumn (for example). Then change column class in our CGridView:

$this->widget('zii.widgets.grid.CGridView', array(
        'id' => 'standard-grid',
        'dataProvider' => $model->search(),
        'filter' => $model,
        'columns' => array(
            'id',
            'field',
            array(
                'class' => 'MyCButtonColumn',
            ),
        ),
    ));

Second, create MyCButtonColumn class in /protected/components/MyCButtonColumn.php

class MyCButtonColumn extends CButtonColumn {
        public $template = '{update} {delete}';
    }

In this example, we simply replace standard template deleting '{view}' button. But what if you want hide delete button in 21 december of 2012?

class MyCButtonColumn extends CButtonColumn {

        protected function checkButtons($data, $id) {
            return !(date('Y-m-d') == '2012-12-21' && $id == 'delete');
        }

        protected function renderDataCellContent($row, $data) {
            $tr = array();
            ob_start();
            foreach ($this->buttons as $id => $button) {
                if ($this->checkButtons($data, $id)) {
                    $this->renderButton($id, $button, $row, $data);
                }
                $tr['{' . $id . '}'] = ob_get_contents();
                ob_clean();
            }
            ob_end_clean();
            echo strtr($this->template, $tr);
        }

    }