Change attribute value in DetailView widget

I have a table called Play, and I show the details of each entry in the widgets in the detail view of Yii2. I have an attribute in this recurring table that has type tinyint, it can be 0 or 1. But I do not want to treat it as a number, instead I want to display yes or no based on the value (0 or 1).

I am trying to change this using a function in a widget detailview, but I get an error: Object of class Closure could not be converted to string

Code of my detailed information:

  <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'name', 'max_people_count', 'type', [ 'attribute' => 'recurring', 'format'=>'raw', 'value'=> function ($model) { if($model->recurring == 1) { return 'yes'; } else { return 'no'; } }, ], 'day', 'time', ... 

Any help would be appreciated!

+8
yii2 detailview
source share
2 answers

Try

 'value' => $model->recurring == 1 ? 'yes' : 'no' 
+13
source share

Unlike GridView , which handles a set of models, DetailView handles only one. Therefore, there is no need to use closure, since $model is the only model to display and is available as a variable.

You can definitely use the solution suggested by rkm , but there is a simpler option.

By the way, you can simplify the condition a bit, since the allowed values ​​are only 0 and 1 :

 'value' => $model->recurring ? 'yes' : 'no' 

If you want to display the value only as a boolean, you can add a formatting suffix with a colon:

 'recurring:boolean', 

'format' => 'raw' is redundant here because it is just text without html.

If you want to add additional parameters, you can use this:

 [ 'attribute' => 'recurring', 'format' => 'boolean', // Other options ], 

Using formatting is a more flexible approach, as these labels will be generated depending on the language of the application installed in config.

Official Documentation:

See also this question , it is very similar to yours.

+14
source share

All Articles