返回

Yii2 ActionColumn 在搜索模型下行索引始终为 0 问题解决

php

在 Yii2 中使用基于搜索模型的 ActionColumn 时,
ActionColumn 中的密钥始终为 0

概述

在 Yii2 中使用 ActionColumn 可以轻松地向网格视图添加操作列。但是,当使用基于搜索模型的数据提供者时,你会遇到一个问题,即 $key 始终为 0。

问题的原因

这个问题发生在搜索模型返回分页结果集时。ActionColumn 中的 $key 不是指数据模型中的主键,而是指搜索结果中的行索引,它始终从 0 开始。

解决方案

要解决此问题,需要在 ActionColumn 中指定 key 属性,该属性指定数据模型中的主键列。示例如下:

[
    'class' => 'kartik\grid\ActionColumn',
    'dropdown' => false,
    'width' => '150px',
    'template' => '{approve} {print-request}',
    'vAlign' => 'top',
    'key' => 'id',  // Specify the primary key column name
    'urlCreator' => function ($action, $model, $key, $index) {
        return Url::to([$action, 'id' => $key]);
    },
    'buttons' => [
        'approve' => function ($url, $model, $key) {
            return Html::a( $key, Url::to(['request-bisa-approve/approve', 'id' => $key]),
                [
                    'class' => 'btn btn-sm btn-primary btn-gii-action-customized fa fa-thumbs-o-up',
                    'role' => 'modal-remote',
                    'data-toogle' => 'tooltip',
                    'title' => 'Reminder IT'
                ]);
        },
    ],
],

好处

指定 key 属性后,ActionColumn 将使用主键列作为行索引,从而确保在创建操作链接时使用正确的主键值。

结论

当使用基于搜索模型的 dataProvider 时,指定 key 属性至关重要。这将确保正确使用数据模型中的主键列,从而实现与数据的有效交互。

常见问题解答

  1. 什么是搜索模型?
    一个特殊的数据提供者,它让你可以根据用户输入的搜索条件过滤和排序数据。
  2. 为什么密钥始终为 0?
    因为在搜索结果中,行的索引从 0 开始,而不是使用主键值。
  3. 如何指定主键列?
    ActionColumn 中使用 key 属性。
  4. 使用 key 属性有什么好处?
    确保在创建操作链接时使用正确的主键值。
  5. 什么时候需要使用 key 属性?
    当使用基于搜索模型的 dataProvider 时。