Dark Cyber
Dark Cyber

Reputation: 2231

Yii2 gridview format property base on output?

I am new in yii2, by default my field in gridview is decimal but I have some condition in value property.

my code view looks like this

[
            'attribute' => 'harga_diskon_periode',
            'format' => function($model){
                if($model->diskon_now == ""){
                    return "text";
                }else{
                    return "decimal";
                }               
            },
            'value' => function($model){
                if($model->diskon_now == ""){
                    return "Tidak ada diskon";                      
                }
            },
         ],

So what I need is, if output number the format will be decimal and if output string the format will be text.

With above code I get this error

Object of class Closure could not be converted to string

I read this http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html#$format-detail it'show string|array so I use anonymous function in format property.

Am I wrong? What's wrong with my code? How should my code looks like? any reference will be appreciated as I'm new to yii2.

Thanks in advance.

Upvotes: 1

Views: 500

Answers (1)

Bizley
Bizley

Reputation: 18021

GridView does not allow closure there, do it like that:

'attribute' => 'harga_diskon_periode',
'value' => function ($model) {
    return $model->diskon_now == ''
        ? 'Tidak ada diskon'
        : \Yii::$app->formatter->asDecimal($model->harga_diskon_periode);
},

Upvotes: 1

Related Questions