YII框架中自帶的表單,搜尋,分頁程式碼的實現

Smile李先生發表於2016-10-13

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框架中自帶的表單,搜尋,分頁程式碼的實現

相關文章