12

我有一个 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'],
     ],
 ]);
?>

姓名 | cm_name | 平台

帐户1 | 杰克| btn1 btn2

其中 btn1 和 btn2 指的是 facebook 和 twitter。

对不起毁容的桌子。

4

2 回答 2

29

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.

于 2014-04-28T18:10:11.173 回答
3

提示:如果您要渲染复杂数据,这在 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]);
      },
    ]
  ]
]);

或者你可以使用

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

部分视图可能类似于

<?= 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) ?>
于 2015-08-08T14:45:53.457 回答