Yii2 formatter - create custom format

2.9k views Asked by At

I would like to create my own format option for DetailView and GridView. I'm now using available formatter options like datetime:

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

I'd like to have my own formatter like this:

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

Where color would translate colorId (which is int - identifier of color) into color name. I know that I can have a function / virtual attribute in the model, but I would like to use it anywhere, not only on that certain model. I've been searching but found only that I need to have specific formatter.

1

There are 1 answers

1
karpy47 On BEST ANSWER

You could extend the Formatter class and handle 'color' as a new type of format. Something like this...

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';
        }
    }
}

Then switch to using this new formatter by changing your config...

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

Now you should be able to use the color format in a gridview/datacolumn like you asked:

'colorId:color'

...or in general by calling the app's formatter component:

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

Please note, this code is NOT tested and bugs might be included.