30分钟搞定yii的gridview,你可能只看这一篇就够了 (包含基本配置,下拉筛选,多选删除)

view代码

<?php
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */
use yii\helpers\Url;
use yii\helpers\Html;
use common\helps\Helps;
use common\helps\ArrayHelper;
use yii\grid\GridView;
use backend\models\User;
use yii\widgets\ActiveForm;
//use yii\bootstrap\ActiveForm;
?>

<?php 
//gridview最外层加入表单,方便全选提交,会影响下拉筛选,如果没有下拉筛选可以用
//    $form=ActiveForm::begin([
//        'id'=>'Form',
//        'enableClientValidation'=>false, 
//        'action'=>'javscript:;'
//    ]);
?>
<div class="row">
    <div class="col-xs-12">
          <div class="box">
            <div class="box-header">
              <h3 class="box-title">考勤列表</h3>
            </div>
            <!-- /.box-header -->
            <div class="box-body table-responsive">   
             <?php
                    echo GridView::widget([
                            'dataProvider' => $dataProvider,
                            'filterModel' => $searchModel,
                            //默认layout的表格三部分可不写:几条简介,表格,分页;可以去掉任意部分 
                            //'layout' => "{summary}\n{items}\n{pager}" ,
                            //没有数据时候显示的内容和html样式
                            'emptyText'=>'当前没有内容',
                            'emptyTextOptions'=>['style'=>'color:red;font-weight:bold'],
                            //给所有的行属性增加id,或class,方便后面选择后整行改变颜色
                            'rowOptions'=>function($model){
                                return ['id'=>"tr-".$model->id];
                            },  
                            //显示底部(就是多了一栏),默认是关闭的
                            'showFooter'=>true,
                            'columns' => [
                                //ActionColumn 显示操作按钮等CheckboxColumn 显示复选框RadioButtonColumn 显示单选框SerialColumn 显示行号
                                [
                                    'class' => 'yii\grid\CheckboxColumn',
                                    //'cssClass'=>'_check',//不能用????后面有js实现的
                                    //底部第一列占6格,其他列隐藏,形成合并1个单元格效果
                                    'footerOptions'=>['colspan'=>6],
                                    'footer'=>'<a href="javascript:;" class="_delete_all" data-url="'.Yii::$app->urlManager->createUrl(['/attend/delete_all']).'">删除全部</a>',
                                    
                                ],
                                    //'nickname',//默认内容搜索,需要输入文字
                                [  
                                    //header 可以解析html代码,将表头默认的点击排序改为添加一个链接
                                    'header'=>'<a href="www.baidu.com">员工姓名2</a>',
                                    //label标题会默认覆盖原来的uid名字(即显示员工姓名不显示用户id),不能解析html
                                    'label'=>'员工姓名',
                                    'attribute'=>'uid',
                                    'value' => function ($data) {
                                        //$arr=Helps::get_correspond_list("get_nickname_list", 'id', "nickname");
                                        $arr=ArrayHelper::map(User::find()->all(),'id','nickname');
                                        return $arr[$data->uid];//返回搜索值
                                    },
                                    'filter' => Helps::get_correspond_list("get_nickname_list", 'id', "nickname"),//下拉选择内容
                                    'footerOptions'=>['class'=>'hide'],//隐藏底部的当前列
                                    //'footerOptions'=>['style'=>'display:none'],//也可以        
                                ],
                                [
                                    'attribute'=>'astart',
                                    'format'=>['date', 'php:Y-m-d H:i:s'],
                                    //关闭默认的点击表头排序,字体将变黑色,蓝色的表示可以点击排序
                                    'enableSorting'=>false,
                                    //如果sign=1不显示此列,否则显示
                                    'visible'=>$sign==1 ? false : true,
                                    //'value'=>function($data){
                                    //    return date('Y-m-d H:i:s',$data->create_time);
                                    //}
                                    'footerOptions'=>['class'=>'hide'],
                                ],
                                [
                                    'attribute'=>'aend',
                                    'value' => function ($data) {
                                        return Helps::time_to_date($data->astart);
                                    },
                                    'footerOptions'=>['class'=>'hide'],
                                ],
                               
                                [
                                    'attribute'=>'state',
                                    'value' => function ($data) {
                                        $arr=Helps::get_attend_status_label();
                                        return $arr[$data->state];
                                    },
                                    'filter' => Helps::get_attend_status(),
                                    'format' => 'raw', //显示label样式,否则显示html代码
                                    'footerOptions'=>['class'=>'hide'],        
                                ],
                                [
                                    'class' => 'yii\grid\ActionColumn',
                                    //控制
                                    "header" => "操作",
                                    'headerOptions' => ['width' => '100'],
                                    'template'=>'{get} {yes} {no} {update} {delete}',
                                    //下面buttons可以不写delete函数,delete默认调用当前控制器下面的delete方法
                                    "buttons" => [
                                        "delete"=>function ($url, $model, $key) {//print_r($key);exit;
                                            return "<a href='javascript:;' class='_delete' data-url='".Yii::$app->urlManager->createUrl(['/attend/delete_js','id'=>$model->id])."'>删除</a>";
                                        },
                                        "update"=>function ($url, $model, $key) {//print_r($key);exit;
                                        //$model 为当前的1条数据
                                        //key就是id
                                        //$url就是根据id自动拼出链接 /attend/update?id=156
                                            $str='';
                                            $str=Html::a('<span class="glyphicon glyphicon-pencil"></span>', Url::to(['attend/edit','id'=>$model->id]), ['title'=>'修改']);
                                            return $str;
                                        },
                                    ],
                                    'footerOptions'=>['class'=>'hide'],
                                ],
                            ]
                     ]);
                    ?>
          <!-- /.box -->
        </div>
</div>
<?php     //ActiveForm::end();   ?>    
<style>
    .select_bg{ background:BCC8D0;  }
</style>
<script>
     $("input[name='selection[]']").addClass("_check");
     //选中改变颜色
     $("._check").click(function(){
         var id=$(this).val();
         console.log(id);
         if($("#tr-"+id).hasClass("select_bg")){
            $("#tr-"+id).removeClass("select_bg");    
         }else{
            //$("#tr-"+id).css("background-color",'red');
            $("#tr-"+id).addClass("select_bg");
         }   
     });
     $("._delete").click(function(){
         var url=$(this).attr('data-url');
         console.log(url);
         $.getJSON(url,{},function(d){
            if(d.done==true){
                alert('删除成功');
                window.location.href="<?=Url::to(['attend/index'])?>";
            }else{
                alert(d.error);
            } 
         });
    });
    $("._delete_all").click(function(){
        var many_check=$("input[name='selection[]']:checked");
        var ids="";
        $(many_check).each(function(){
            ids+=this.value+',';                       
        });
        //去掉最后一个逗号
        if (ids.length > 0) {
            ids = ids.substr(0, ids.length - 1);
        }else{
            alert('请选择至少一条记录!'); return false;
        }
        var url=$(this).attr('data-url');
        $.post(url,{ids},function(d){
            console.log(d);
            if(d.done==true){
                console.log(1);
                alert('删除成功!');
                window.location.href="<?=Url::to(['attend/index'])?>";
            }else{
                alert(d.error);
            } 
        },'json');
    });
</script>

controller代码

<?php
namespace backend\controllers;

use Yii;

use backend\models\Attend;
use backend\models\AttendSearch;
use yii\data\Pagination;
use common\helps\ArrayHelper;
use backend\models\User;
use yii\helpers\Json;


class AttendController extends SiteController
{
    public function actionIndex(){
        
        $searchModel = new AttendSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->get());
        $sign=Yii::$app->request->get('sign');
        return $this->render('index',
        [
            "dataProvider"=>$dataProvider,
            "searchModel"=>$searchModel,
            "sign"=>$sign,
        ]);
    }
    /*
     * 操作链接使用的单个删除
     */
    public function actionDelete(){
        $id=Yii::$app->request->get('id');
        $model = Attend::findOne($id);        
        $model->delete();
        return $this->redirect(['attend/index']);
    }
    /*
     * 操作js使用的单个删除
     */
    public function actionDelete_js($id){
        try{
            $model = Attend::findOne($id);        
            $model->delete();
            echo Json::encode(['done'=>true]);
        } catch (Exception $e) {
            echo Json::encode(['done'=>false,'error'=>$e->getMessage()]);
        }
    }
    /*
     * 多选删除js
     */
    public function actionDelete_all(){
        try{
            $ids=Yii::$app->request->post('ids');
            $ids=explode(',',$ids);
            //数组直接查询
            $lists = Attend::find()->where(['in','id',$ids])->all();     
            foreach($lists as $list){
                $list->delete();
            }
            echo Json::encode(['done'=>true]);
        } catch (Exception $e) {
            echo Json::encode(['done'=>false,'error'=>$e->getMessage()]);
        }
    }
 
}

model代码

<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;

class AttendSearch extends Attend
{
    public function rules()
    {
        // 只有在 rules() 函数中声明的字段才可以搜索,不声明不显示搜索框
        return [
           [['id','uid','username','nickname','time','state'], 'safe'],
        ];
    }

    public function scenarios()
    {
        // 旁路在父类中实现的 scenarios() 函数
        return Model::scenarios();
    }

    public function search($params){
        $query = Attend::find();
        
        if(!Yii::$app->request->get('sort')){
            $query->orderBy('id desc');
        }

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

        // 从参数的数据中加载过滤条件,并验证
        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }
        // 增加过滤条件来调整查询对象
        $query->andFilterWhere(['=', 'nickname', $this->nickname])
              ->andFilterWhere(['=', 'uid', $this->uid])
              ->andFilterWhere(['=', 'state', $this->state]);

        return $dataProvider;
    }
}

 

<?php
namespace backend\models;

//web后端
use Yii;
use common\helps\ArrayHelper;
use backend\models\User;
use backend\models\Worktime;


class Attend extends\yii\db\ActiveRecord
{    
    public static function tableName()
    {
        return 'attend';
    }
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'uid' => '员工id',
            'username' => '员工邮箱',
            'nickname' => '员工名',
            'astart' => '上班签到',
            'thresholdon' => '上班签到',
            'aend' => '下班打卡',
            'thresholdoff' => '上班签到',   
            'time' => '统计',
            'state' => '状态',
        ];
    }
}  

 

参考

http://www.maomaonv.com/site-index.html

 

posted on 2017-03-01 15:50  coderWilson  阅读(9847)  评论(0编辑  收藏  举报

导航