yii2 gridview toggle column

被刻印的时光 ゝ 提交于 2019-12-19 10:18:09

问题


I am new to yii2. and learning it slowly. I am using yii2 gridview in my project I want to show hide columns dynamically. requires something like this [https://datatables.net/examples/api/show_hide.html =>demo is given in this link] but cant understand how to do this? can anybody help?

code=>

<?php 

    $gridColumns = [
                     ['class' => 'yii\grid\SerialColumn'],
                     ['class' => 'yii\grid\CheckboxColumn'],  
[
                    'header' => '<input type="checkbox"> Name',//onclick of this checkbox show / hide the column 
                    'attribute'=>'name',                                          
                ],   
                    'company_mail', 
                    'no_employees',
                    'email:email', 
                    .
                    .
                    .];
            echo GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => $gridColumns,
    ]); 
    ?>

also tried like this=> 'visible'=>false, but it hides permanently... where to add if() condition ??

how to solve this ..can anyone solve?

also [Toggle Column visibility in Yii Framework is for cgridview can i use this one in yii2]


回答1:


This is done using JavaScript or jQuery. The example you gave uses jQuery. If you inspect the page, you can find all bits of code you need to get this working.

Links that toggle columns have data-column attribute which contains the number of the column (starting with 0):

<a class="toggle-vis" data-column="0">Name</a>

The page contains script, which toggles the column by it's number (using DataTables plug-in):

$(document).ready(function() {
    //getting the table that we will be working with
    var table = $('#example').DataTable( {
        "scrollY": "200px",
        "paging": false
    } );

    $('a.toggle-vis').on( 'click', function (e) {
        e.preventDefault();

        // Get the column by number
        var column = table.column( $(this).attr('data-column') );

        // Toggle the visibility
        column.visible( ! column.visible() );
    } );
} );

Here is a simple script that will work with previously mentioned links (in this case - starting with 1) and any table (just switch #example with your gridview's id):

$(document).ready(function() {
    $('a.toggle-vis').on('click', function(e) {
        var column = $(this).attr('data-column');
        $('#example th:nth-child(' + column + '), #example td:nth-child(' + column + ')').toggle();
    });
});

Give gridview table id:

echo GridView::widget([
       'tableOptions' => ['id' => 'example'],
       'class' => 'table table-striped table-bordered'
])


来源:https://stackoverflow.com/questions/46968615/yii2-gridview-toggle-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!