Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

yii2 - Changing value of an attribute in DetailView widget

I have a table named Play and I'm showing details of each record in Yii2 detail view widget. I have an attribute in that table recurring which is of type tinyint, it can be 0 or 1. But I don't want to view it as a number, instead i want to display yes or no based on the value (0 or 1).

I'm trying to change that with a function in detailview widget but I'm getting an error: Object of class Closure could not be converted to string

My detail view code:

 <?= 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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unlike GridView which processes a set of models, DetailView processes just one. So there is no need for using closure since $model is the only one model for display and available in view as variable.

You can definitely use solution suggested by rkm, but there is more simple option.

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

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

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

'recurring:boolean',

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

If you want add more options, you can use this:

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

Using formatter is more flexible approach because these labels will be generated depending on application language set in config.

Official documentation:

See also this question, it's quite similar to yours.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...