【问题标题】:Yii2 DataGrid different buttons set for the first and last rowYii2 DataGrid为第一行和最后一行设置不同的按钮
【发布时间】:2018-03-12 12:39:49
【问题描述】:

我需要对 DataGrid 中的行重新排序,因此我为每一行添加了两个按钮“向上”和“向下”:

        <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            [
                'headerOptions' => ['style' => 'width:56px'],
                'class' => 'yii\grid\ActionColumn',
                'template' => '{Up} {Down}',
                'buttons' => [
                    'Up' => function($url, $model, $key) {
                        return Html::a('',['/admin/content/up', 'id' => $key], ['class' => 'glyphicon glyphicon-chevron-up']);
                    },
                    'Down' => function($url, $model, $key) {
                        return Html::a('',['/admin/content/down', 'id' => $key], ['class' => 'glyphicon glyphicon-chevron-down']);
                    },
                ]
            ],
            'content'
        ]
    ]);
    ?>

没有分页,所有数据都适合一页。现在看起来像:

我想让它看起来更整洁:

所以我需要分别隐藏第一行和最后一行的“向上”和“向下”按钮。无法知道如何制作,甚至无法从匿名按钮功能中获取行号。

【问题讨论】:

  • ActionColumn 有属性 "visibleButtons" 并且在回调函数function ($model, $key, $index) $index 是行号
  • 你试试这个$count = $dataProvider-&gt;getTotalCount(),然后在你的操作列中添加这个属性'visibleButtons' =&gt; [ 'Up' =&gt; function ($model, $key, $index) { return $index == 0 ? false : true; }, 'Down' =&gt; function ($model, $key, $index) use ($count) { return $index == ($count - 1) ? false : true; }]
  • 谢谢,它有效!
  • @NimishaMolia 您应该提供一个正常的答案,而不是将解决方案放入 cmets。对他人有帮助,你会获得一些声誉。
  • @robsch,当然,下次我会这样做

标签: php datagrid yii2


【解决方案1】:

试试这个

$count = $dataProvider->getTotalCount(); 

然后在您的操作列中添加此属性

'visibleButtons' => [
    'Up' => function ($model, $key, $index) {
         return $index == 0 ? false : true; 
     }, 
    'Down' => function ($model, $key, $index) use ($count) { 
         return $index == ($count - 1) ? false : true; 
     }
]

【讨论】:

  • 我喜欢你的解决方案。您也可以在模型 isItFirst 和 isItLast 中创建函数。检查并显示或隐藏它取决于结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 2015-10-10
  • 2014-07-18
  • 1970-01-01
  • 2017-02-17
相关资源
最近更新 更多