Home > php教程 > php手册 > body text

利用yii2 gridview实现批量删除案例,yii2gridview

WBOY
Release: 2016-06-13 08:41:24
Original
1062 people have browsed it

利用yii2 gridview实现批量删除案例,yii2gridview

作者:白狼 出处:http://www.manks.top/article/yii2_gridview_deleteall本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

今天仍然继续探讨GridView的问题,昨天有个小伙伴留言说你用gridview给我去掉表头的链接?我想啊想,这用gridview确实不容易实现,至少我没想出来,会的下方可留言。但是呢,这根gridview有个毛线关联啊,明明是要设置ActiveDataProvider,你要我怎么用gridview实现嘛。

这个问题也是很简单的,我们来看看具体实现

<span>$dataProvider</span> = <span>new</span><span> ActiveDataProvider([ 
</span>'query' => <span>$query</span>,<span> 
]); 
</span><span>$dataProvider</span>->setSort(<span>false</span>);
Copy after login

分分钟搞定不是事。

好了,我们来谈谈主题:如何利用yii2 gridview实现批量删除?

我先说一下几个步骤啊,免得直接贴代码有的小伙伴删了一句去了一句最后失败了!

1、gridview设置options时增加一个id 这里我们命名grid

'options' =><span> [
</span><span>//</span><span> ...其他设置项</span>
'id' => 'grid'<span>
]</span>,
Copy after login

2、columns增加选项复选框,批量删除必然不可少了复选框操作,这里我们的name值设定为id,方便对数据操作

<span>[
    </span>'class' => 'yii\grid\CheckboxColumn',
    'name' => 'id',<span>
]</span>,
Copy after login

3、页面上我们增加一个批量删除按钮,注意这里我们增加了一个class gridview,方便后面js实现点击效果

<?= Html::a('批量删除', "javascript:void(0);", ['class' => 'btn btn-success gridview']) ?>
Copy after login

4、最后一步,写js实现按钮操作,打开你的console看看,我们很轻松的就拿到了选中的行的id,然后这里就可以异步操作数据了。

<?<span>php
</span><span>$this</span>->registerJs('<span>
$(".gridview").on("click", function () {
//注意这里的$("#grid"),要跟我们第一步设定的options id一致
    var keys = $("#grid").yiiGridView("getSelectedRows");
    console.log(keys);
});
</span>'<span>);
</span>?>
Copy after login

下面贴上完整代码

GridView::<span>widget([
        </span><span>//</span><span> ......</span>
        'options' => ['class' => 'grid-view','style'=>'overflow:auto', 'id' => 'grid'],
        <span>//</span><span> ......</span>
        'columns' =><span> [
            </span><span>//</span><span> ......</span>
<span>            [
                </span>'class' => 'yii\grid\CheckboxColumn',
                'name' => 'id',<span>
            ]</span>,
            <span>//</span><span> ......</span>
        ],<span>
]);
</span><span>$this</span>->registerJs('<span>
$(".gridview").on("click", function () {
    var keys = $("#grid").yiiGridView("getSelectedRows");
    console.log(keys);
});
</span>');
Copy after login

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template