php 如何在yii2的gridView中创建自定义ActionColumn?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23342035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a custom ActionColumn in the gridView of yii2?
提问by tareq
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,我设法让它包含我需要的数据,但我接下来需要做的是创建一个列,其中包含 has_facebook 和 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
姓名 | cm_name | 平台
account1 | Hyman | btn1 btn2
帐户1 | Hyman| btn1 btn2
where btn1 and btn2 refer to facebook and twitter.
其中 btn1 和 btn2 指的是 facebook 和 twitter。
sorry for the disfigured table.
很抱歉这张毁容的桌子。
回答by Alex
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:
命名回调函数。CComponent 中有核心方法evaluateExpression:
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_arrayand pass into it your model.
在我们的例子中,表达式不是字符串,它是一个函数,所以它运行 php 方法call_user_func_array并将您的模型传递给它。
回答by amit bakle
Just a tip: If you are rendering complex data, this was would be helpful in Yii2..
只是一个提示:如果你正在渲染复杂的数据,这在 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) ?>