Search code examples
yiicgridview

remove button from CGridView with condition


Hi I have CRUD generated CGridView in yii. I need to add a new button to CGridView rows and hide it if appointment_status(one of CGridView column) value equals 0

This is my code of CGridView,

$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'bookings-grid',
    'dataProvider' => $model->search(),
    'filter' => $model,
    'columns' => array(
        'id',
        'name',
        'email',
        'telephone',
        'time',
        'employee',       
        'appointment_status',
        'client_ip',
        'link' => array(
            'header' => 'Confirmation',
            'type' => 'raw',
            'value' => 'CHtml::button("$data->appointment_status",array("onclick"=>"document.location.href=\'".Yii::app()->controller->createUrl("controller/action",array("id"=>$data->id))."\'"))',
            'visible'=>$data->appointment_status==1,
        ),
        array(
            'class' => 'CButtonColumn',
        ),
    ),
));

But all I'm getting is error stating,

Undefined variable: data

It would be great help if someone can look into it.


Solution

  • Your 'visible' handling the column visibility and not the button, you can use custom attribute on model to create and handle the button visibility.

    add to your model:

    public function getConfirmationButton()
    {
       if ($data->appointment_status == 1) {
          return CHtml::button($this->appointment_status,array("onclick"=>"document.location.href=\'".Yii::app()->controller->createUrl("controller/action",array("id"=>$this->id))."\'"));
       } else {
          return '';
       }
    }
    

    and call it in your view:

    ..........
    'link' => array(
            'header' => 'Confirmation',
            'type' => 'raw',
            'value' => '$data->confirmationButton',
        ),
    ...........