Yii2-如何在网格视图中添加搜索框
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yii2-如何在网格视图中添加搜索框相关的知识,希望对你有一定的参考价值。
我是Yii-2的新手。我的索引页面中有一个网格视图,其中显示了一些条目。
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yiigridSerialColumn'],
//'meter_id',
[
'label' => 'Meter MSN',
'value' => function ($d) {
return $d->meter->meter_msn;
},
// 'filter' => html::activeDropDownList($searchModel, 'meter_id', appmodelsMeters::toArrayList(), ['prompt' => "All Meters", 'class' => 'form-control']),
],
'imsi',
'telecom',
'status',
[
'label' => 'Created By',
'value' => function ($data) {
if (is_object($data))
return $data->created->name;
return ' - ';
},
//'filter' => Html::activeDropDownList($searchModel, 'created_by', appmodelsUser::toArrayList(), ['prompt' => "Created By", 'class' => 'form-control']),
],
'comments',
'historic',
['class' => 'yiigridActionColumn'],
],
]); ?>
现在我想为Meter MSN
添加一个搜索框。在上面的代码中,过滤器被隐藏,因此它正在工作,但我不想添加下拉列表,而是我想要一个搜索框。
以下是我的搜索课程
public function search($params)
{
$query = MetersInventoryStore::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'meter_id' => $this->meter_id,
'created_by' => $this->created_by,
'updated_by' => $this->updated_by,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'store_id' => $this->store_id,
'meter_serial'=>$this->meter_serial,
// 'historic' => $this->historic,
'status'=>'SIM Installed',
])
// ->orFilterWhere(['status'=>'Communication Failed'])
;
// $query->andFilterWhere(['like', 'meter_serial', $this->meter_serial])
// ->andFilterWhere(['like','meter_id',$this->meter_id]);
$query->orderBy(['id' => SORT_DESC]);
return $dataProvider;
}
如何在其中放置搜索框?由于简单搜索类默认会设置搜索功能。但我的MSN
值来自一个函数,所以我不知道如何放置搜索框。任何帮助将受到高度赞赏。
答案
要在计算列中添加过滤器字段,您应在搜索模型中添加公共变量
public function search($params)
{
public $your_column;
// declare as safe
public function rules()
{
return [
...
[[ 'your_column', ], 'safe'],
];
}
$query = MetersInventoryStore::find();
然后在grid_view中引用your_column
...
'columns' => [
['class' => 'yiigridSerialColumn'],
//'meter_id',
[
'attribute' => 'your_column',
'label' => 'Meter MSN',
'value' => function ($d) {
return $d->meter->meter_msn;
},
],
最后你的searchModel必须扩展你的过滤条件,以便根据你传递的过滤值正确管理你的计算列。
您可以在本教程http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/中找到一些示例
以上是关于Yii2-如何在网格视图中添加搜索框的主要内容,如果未能解决你的问题,请参考以下文章