在我的控制器中,我渲染了$dataProvider
$searchModel = new StudentSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index',[ 'searchModel' => $searchModel,'dataProvider' => $dataProvider,]);
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; }