Yii2格式化程序 - 创建自定义格式

时间:2017-09-07 07:07:43

标签: gridview yii2 formatter detailview

我想为DetailView和GridView创建自己的格式选项。我现在使用可用的格式化程序选项,例如datetime:

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'current_date:datetime'
       ]
]?>

我想拥有自己的格式化程序:

 <?= DetailView::widget([
            'model' => $model,
            'attributes' => [
                'current_date:datetime',
                'colorId:color'
           ]
    ]?>

其中color将colorId(int - 颜色标识符)转换为颜色名称。我知道我可以在模型中有一个函数/虚拟属性,但我想在任何地方使用它,而不仅仅是在某个模型上。我一直在搜索,但发现我只需要specific formatter

1 个答案:

答案 0 :(得分:5)

您可以扩展Formatter类并处理&#39; color&#39;作为一种新型格式。像这样......

class MyFormatter extends \yii\i18n\Formatter
{
    public function asColor($value)
    {
        // translate your int value to something else...
        switch ($value) {
            case 0:
                return 'White';
            case 1:
                return 'Black';
            default:
                return 'Unknown color';
        }
    }
}

然后通过更改配置切换到使用这个新的格式化程序...

'components' => [
    'formatter' => [
        'class' => '\my\namespace\MyFormatter',
        // other settings for formatter
        'dateFormat' => 'yyyy-MM-dd',
   ],
],

现在你应该能够像你问的那样在gridview / datacolumn中使用颜色格式:

'colorId:color'

...或者通常通过调用应用程序的格式化程序组件:

echo Yii::$app->formatter->asColor(1);  // 'Black'

请注意,此代码未经过测试,可能包含错误。

相关问题