Yii2-如何在网格视图中添加搜索框

时间:2017-12-28 07:45:32

标签: search gridview yii2

我是Yii-2的新手。 我的索引页面中有一个网格视图,其中显示了一些条目。

loss.backward()

现在我想针对<?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], //'meter_id', [ 'label' => 'Meter MSN', 'value' => function ($d) { return $d->meter->meter_msn; }, // 'filter' => Html::activeDropDownList($searchModel, 'meter_id', \app\models\Meters::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', \app\models\User::toArrayList(), ['prompt' => "Created By", 'class' => 'form-control']), ], 'comments', 'historic', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> 添加一个搜索框。在上面的代码中,过滤器被隐藏,因此它正在工作,但我不想添加下拉列表,而是我想要一个搜索框。

以下是我的搜索类

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; } 值来自一个函数,所以我不知道如何放置一个搜索框。 任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:3)

要在计算列中添加过滤器字段,您应该添加pubblic var 在您的搜索模型中

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' => 'yii\grid\SerialColumn'],
    //'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/