yii2 gridview toggle column

2019-02-19 10:19发布

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]

标签: gridview yii2
1条回答
三岁会撩人
2楼-- · 2019-02-19 11:15

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'
])
查看更多
登录 后发表回答