问题
I have placed a conditional statement in my index page.
Controller
$type ="402"; // type can me 401 and 403
$searchModel = new MdcmetersdataSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'type' => $type
]);
Index.php
<?php
if($type == '401')
{
$columns = [
['class' => 'yii\grid\SerialColumn'],
'device_id',
'cust_id',
'msn',
'current_p1',
'current_p2',
'current_p3',
'data_date_time',
['class' => 'yii\grid\ActionColumn'],
];
}else if($type == '402')
{
$columns = [
['class' => 'yii\grid\SerialColumn'],
'device_id',
'cust_id',
'msn',
'voltage_p1',
'voltage_p2',
'voltage_p3',
'data_date_time',
['class' => 'yii\grid\ActionColumn'],
];
}
else if($type == "403")
{
$columns = [
['class' => 'yii\grid\SerialColumn'],
'device_id',
'cust_id',
'msn',
'kwh',
'data_date_time',
['class' => 'yii\grid\ActionColumn'],
];
}
else
{
$columns = [
['class' => 'yii\grid\SerialColumn'],
'device_id',
'cust_id',
'msn',
'voltage_p1',
'voltage_p2',
'voltage_p3',
'current_p1',
'current_p2',
'current_p3',
'device_id',
'kwh',
'data_date_time',
['class' => 'yii\grid\ActionColumn'],
];
}
?>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $columns
]);
?>
As mentioned above that the value of $type
can be 401, 402 and 403
. So I am trying to check whether my condition is working or not. So I pass 402
which means only the columns with voltages
value should be shown, but I got the following result
I want to hide the red circled columns, i.e. I just want to show the data of that particular $type
value.
Any help would be highly appreciated.
回答1:
If you want hide/don't show the rows without volt value for 402 the simples way is aavoid selection in search query . For this you could add a proper 402 search funtion in the search model
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
........
return $dataProvider;
}
public function search402($params)
{
$query = YourModel::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andWhere(['not', ['volt1' => null]]);
;
return $dataProvider;
}
and in controller manage the search function you really need
$searchModel = new MdcmetersdataSearch();
switch($type){
case '402':
$dataProvider = $searchModel->search402(Yii::$app->request->queryParams);
break;
....
}
来源:https://stackoverflow.com/questions/61341463/how-to-hide-columns-based-on-condition-in-yii2-gridview