如何为yii2 ListView小部件使用自定义过滤器?

时间:2015-02-21 13:02:10

标签: php yii2

在我的控制器中,我渲染了$ dataProvider

$searchModel = new StudentSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);

这是StudentSearch的搜索功能

public function search($params)
{
    $query = Student::find();

       $query->andFilterWhere([
        'student_id' => $this->student_id,
        'age' => $this->age,

    ]);

    $query->andFilterWhere(['like', 'firstname', $this->firstname]);

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


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

    return $dataProvider;
}

在视图中我在ListView小部件中使用了$ dataprivider,如下所示

  <div class="listView">

   <?php
    echo ListView::widget([
   'dataProvider' => $dataProvider,
    'itemView' => '_student_list',
    ]);
    ?>

  </div>

在'_student_list.php'中我列出了学生

我的过滤器

  <div class="listFilter">
   <input type="text" name="firstname"/>
   <input type="text" name="age"/>
 </div>

现在我希望按名字或年龄过滤学生。我怎样才能做到这一点?如果您有任何解决此问题的方法,请提供帮助。谢谢。

1 个答案:

答案 0 :(得分:6)

1)在您的视图中添加过滤器表单:

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $form yii\widgets\ActiveForm */
?>

<div class="student-form">
    <?php $form = ActiveForm::begin(['method' => 'get']); ?>

    <?= $form->field($searchModel, 'firstname') ?>

    <?= $form->field($searchModel, 'age') ?>

    <div class="form-group">
        <?= Html::submitButton('Apply', ['class' => 'btn btn-success']) ?>
    </div>

    <?php ActiveForm::end(); ?>
</div>

2)根据收到的StundentSearch参数,准备dataProvider模型以返回GET

必须在规则中指定这些属性才能大规模分配它们。

public function rules()
{
    return [
        ['firstname', 'string'],
        ['age', 'integer'],
    ];
}

public function scenarios()
{
    // bypass scenarios() implementation in the parent class
    return Model::scenarios();
}

public function search($params)
{
    $query = Student::find();

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

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

    $query->andFilterWhere(['age' => $this->age])
        ->andFilterWhere(['like', 'firstname', $this->firstname]);

    return $dataProvider;
}