Yii2: how to define a formatter for GridView columns property

hao*_*ang 2 yii2

I have an is_active(tiny-int) field in user table.

Also I define some meanings for is_active:

code in params.php

return [
  'enumData' => [
      'is_active' => [1 => '?', 0 => '×'],
  ]
];
Run Code Online (Sandbox Code Playgroud)

code in 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]

            },
        ],
    ],
]); ?>
Run Code Online (Sandbox Code Playgroud)

Want I want is like this in user\index.php

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
         'is_active:humanReadable',
    ],
]); ?>
Run Code Online (Sandbox Code Playgroud)

I tried to add a helper function, but I was wondered if has a neat way to do that like upon code ?

thanks for any help.

aro*_*hev 5

为什么不为此使用格式化程序?

您可以通过更改$booleanFormat属性来更改布尔值的输出。

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

use Yii;

...

Yii::$app->formatter->booleanFormat = ['×', '?'],
Run Code Online (Sandbox Code Playgroud)

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

'components' => [
    'formatter' => [
        'class' => 'yii\i18n\Formatter',
        'booleanFormat' => ['×', '?'],
    ],
],
Run Code Online (Sandbox Code Playgroud)

然后GridView你可以简单地写:

'is_active:boolean',
Run Code Online (Sandbox Code Playgroud)

更新:

多值情况。

假设我们有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];
}
Run Code Online (Sandbox Code Playgroud)

然后在 GridView 中,您可以像这样输出标签:

[
    'attribute' => 'type',
    'value' => 'typeLabel',
],
Run Code Online (Sandbox Code Playgroud)