Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom ActionColumn in the gridView of yii2?

Tags:

php

yii2

I have a gridView and i managed to get it to contain the data i need, but what i need to do next is to create a column which contains two buttons for has_facebook and has_twitter.

<?=
 GridView::widget([
     'dataProvider'=>$dataProvider,
     'filterModel' =>$searchModel,
     'columns'     =>[
         ['class'=>'yii\grid\SerialColumn'],
         'name',
         'cm_name',
         'has_facebook',
         'has_twitter',             
         ['class'=>'yii\grid\ActionColumn'],
     ],
 ]);
?>

name | cm_name | platforms

account1 | jack | btn1 btn2

where btn1 and btn2 refer to facebook and twitter.

sorry for the disfigured table.

like image 515
tareq Avatar asked Apr 28 '14 13:04

tareq


2 Answers

You don't need to create own column Class. You can create simple raw-column and show there anything you want:

[
    'attribute' => 'some_title',
    'format' => 'raw',
    'value' => function ($model) {                      
            return '<div>'.$model->id.' and other html-code</div>';
    },
],

This function

function ($model) {                      
    return '<div>'.$model->id.' and other html-code</div>';
}

names callback function. There is core method evaluateExpression in CComponent:

public function evaluateExpression($_expression_,$_data_=array())
{
    if(is_string($_expression_))
    {
        extract($_data_);
        return eval('return '.$_expression_.';');
    }
    else
    {
        $_data_[]=$this;
        return call_user_func_array($_expression_, $_data_);
    }
}

in our case expression is not string, it's a function, so it runs php method call_user_func_array and pass into it your model.

like image 197
Alex Avatar answered Nov 11 '22 23:11

Alex


Just a tip: If you are rendering complex data, this was would be helpful in Yii2..

echo yii\grid\GridView::widget([
  'dataProvider' => $dataProvider,
  'columns' => [
    'id',
    [
      'attribute' => 'Details',
      'format' => 'raw',
      'value' => function ($model) {
        return $this->render('//path/to/view.php', ['model' => $model]);
      },
    ]
  ]
]);

or you can use

echo \yii\widgets\ListView::widget([
    'dataProvider' => $dataProvider,
    'itemView' => '//path/to/view.php',
]);

and the partial view could be something like

<?= Html::img('@web/user/images' . $model->id . '.jpeg', ['alt' => 'Profile Picture', 'class' => 'img img-rounded']); ?>
<?= Html::encode($model->firstName) ?> <?= Html::encode($model->lastName) ?>,
living in <?= Html::encode($model->city) ?> <?= Html::encode($model->country) ?>
like image 3
amit bakle Avatar answered Nov 11 '22 22:11

amit bakle