YII框架中自带的表单,搜索,分页代码的实现
YII框架中自带的表单,搜索,分页代码的实现
控制器代码:
先
use yii\data\Pagination;
然后写个控制器/方法
/** * 搜索后分页 */ public function actionList(){ $where=Yii::$app->request->get(); $query=new \yii\db\Query(); $query->from('user'); if(!empty($where['name'])){ $query->andWhere(['name'=>$where['name']]); } if(!empty($where['age1']) && $where['age1']!==""){ $query->andWhere(['>=','age',$where['age1']]); } if(!empty($where['age2']) && $where['age2']!==""){ $query->andWhere(['<=','age',$where['age2']]); } $users=$query->from('user')->all(); // var_dump($users);die; $pages = new Pagination(['totalCount' =>$query->count(),'pageSize'=>'1']); //实例化分页类,带上参数(总条数,每页显示条数) $users = $query->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('list.php',['users'=>$users,'where'=>$where,'pages'=>$pages]); } }接着在视图层
<?php use yii\widgets\ActiveForm; use yii\helpers\Html; use yii\helpers\Url; use yii\widgets\LinkPager; ?> <?php $form=ActiveForm::begin([ 'action'=>Url::toRoute(['show/list']), 'method'=>'get', ]); echo '姓名:'.Html::input('text','name'); echo '年龄区间:'. Html::input('text','age1'); echo '-'.Html::input('text','age2'); echo Html::submitButton(); ActiveForm::end(); ?> <table class="table"> <?php foreach ($users as $user): ?> <tr> <td><?php echo $user['name'] ?></td> <td><?php echo $user['pwd'] ?></td> <td><?php echo $user['age'] ?></td> </tr> <?php endforeach; ?> </table> <?php echo LinkPager::widget([ 'pagination'=>$pages, 'nextPageLabel'=>'下一页', 'firstPageLabel'=>'首页' ]) ?>以上就是YII框架中自带的表单,搜索,分页代码的实现