Yii2:如何为 GridView 列定义格式化程序 属性

Yii2: how to define a formatter for GridView columns property

我在 user table 中有一个 is_active(tiny-int) 字段。

另外我给is_active定义了一些含义:

params.php

中的代码
return [
  'enumData' => [
      'is_active' => [1 => '√', 0 => '×'],
  ]
];

user\index.php

中的代码
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        [
            'attribute' =>   'is_active',
            'format' => 'raw',
            'value' => function ($model) {
                return Yii::$app->params['enumData']['is_active'][$model->is_active]

            },
        ],
    ],
]); ?>

我想要的是这样的user\index.php

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
         'is_active:humanReadable',
    ],
]); ?>

我试图添加一个辅助函数,但我想知道是否有像代码那样的巧妙方法来做到这一点?

感谢您的帮助。

为什么不为此使用 Formatter

您可以通过更改 $booleanFormat 属性.

来更改布尔值的输出

你可以通过formatter组件在运行时完成

use Yii;

...

Yii::$app->formatter->booleanFormat = ['×', '√'],

或全局使用应用程序配置:

'components' => [
    'formatter' => [
        'class' => 'yii\i18n\Formatter',
        'booleanFormat' => ['×', '√'],
    ],
],

然后在GridView中你可以简单地写:

'is_active:boolean',

更新:

多值大小写。

假设我们有 type 属性,将其添加到您的模型中:

const self::TYPE_1 = 1;
const self::TYPE_2 = 2;
const self::TYPE_3 = 3;

/**
 * @return array
 */
public static function getTypesList()
{
    return [
        self::TYPE_1 => 'Type 1',
        self::TYPE_2 => 'Type 2',
        self::TYPE_3 => 'Type 3',
    ];
}

/**
 * @return string
 */
public function getTypeLabel()
{
    return self::getTypesList()[$this->type];
}

然后在 GridView 中你可以这样输出标签:

[
    'attribute' => 'type',
    'value' => 'typeLabel',
],