在YII2中的GridView中设置过滤器

时间:2016-02-06 15:48:42

标签: gridview yii yii2

您好我有一个yii代码,我可以在其中显示模型中的数据,但搜索栏没有在gridview中显示,请帮忙。

Gridview代码:

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

           // 'emp_attendance_pid',
            [

                    'label' => 'Employee ID',
                    'attribute' => 'emp_history_id',
                    'value' => 'emp_history_id',
            ],
            [
                  'label' => Yii::t('app','First Name'),
                 // 'attribute' => 'emp_history_id',
                  'value' => 'empHistory.emp_first_name',
                'filter' => ArrayHelper::map(app\modules\employee\models\EmpInfo::find()->all(), 'emp_info_id', 'emp_first_name')
            ],
            [
                  'label' => Yii::t('app','Last Name'),
                 // 'attribute' => 'emp_history_id',
                  'value' => 'empHistory.emp_last_name',
                'filter' => ArrayHelper::map(app\modules\employee\models\EmpInfo::find()->all(), 'emp_info_id', 'emp_last_name')
            ],

在这里你可以看到过滤器,因为我能够使用arrayhelper获取数据,但我需要获取我在搜索框中提供的数据,搜索框也没有到来,只有下拉才会出现

1 个答案:

答案 0 :(得分:1)

过滤需要参数属性

如果您定义过滤器属性,则会有一个下拉列表。 据我所知,你想要输入文字,因此你不需要过滤。

如果要通过相关表进行搜索,则应在SearchModel中创建公共属性并创建验证规则。正如我从您的示例中看到的,您想要从相关表中过滤数据;

这是一个小例子:

设置搜索模型

 public $emp_first_name;

 public function rules() 
 {
    return [
        [['emp_first_name'], 'safe']
    ];
 }

 public function search($params) 
 {
     $query = Person::find()->joinWith(['empHistory'])->groupBy(Person::tableName().'.id');

     $dataProvider = new ActiveDataProvider([
         'query' => $query,
     ]);

     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }

     $query->andFilterWhere(['like', EmpInfo::tableName().'.emp_first_name', $this->emp_first_name]);

     return $dataProvider;
}

在视图中

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'emp_history_id',
        [
            'attribute' => 'emp_first_name',
            'value' => 'empHistory.emp_first_name',
        ],
        ['class' => 'yii\grid\ActionColumn'],
    ]
]); ?>
相关问题