Yii2 Gridview:我目前使用哪种dataProvider?

时间:2017-07-12 10:21:10

标签: gridview yii2 dataprovider

我在同一页面上有两个gridView小部件,每个小部件都有自己的数据提供程序,如下所示:

<?= GridView::widget([
    'dataProvider' => $userModel,
    'columns' => $columns,
]); ?>

<?= GridView::widget([
    'dataProvider' => $companyModel,
    'columns' => $columns,
]); ?>

两个视图中的列大致相似,但前三列中存在一些差异。我想要做的是确定当前正在编译哪个窗口小部件,以便我可以为该窗口小部件动态创建适当的列。例如:

<?php     
$columns=[];

// here is where the problem is. I would like to do something along these lines:  
if(GridView->dataProvider->id == 'userModel')
  {    
     // add custom columns    
     $columns[] = 'userName'; 
  } else {    
     // etc... 
  }

// common columns used by both grids here 
$columns[] = [
    'totalCount',
    'totalCost',
 ];

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

解决。

首先创建您的公共列:

// common columns used by both grids here 
$columns = [];
$columns[] = [
    'totalCount',
    'totalCost',
 ];

然后按如下方式创建和合并自定义列:

 // user specific columns
$userColumns = [];
$userColumns[] = //... 
// now merge with common columns
$userColumns = array_merge($userColumns,$columns);

现在从网格小部件中调用相应的列:

<?= GridView::widget([
    'dataProvider' => $userModel,
    'columns' => $userColumns,
]); ?>