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

前端之家收集整理的这篇文章主要介绍了php – 如何为yii2 ListView小部件使用自定义过滤器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的控制器中,我渲染了$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)在您的视图中添加过滤器表单:
<?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)根据收到的GET参数准备StundentSearch模型以返回dataProvider.

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

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',$this->firstname]);

    return $dataProvider;
}
原文链接:https://www.f2er.com/php/133989.html

猜你在找的PHP相关文章