Search code examples
gridviewviewyii2detailview

Yii2: Remove "(not set)" in GridView and DetailView for null values


How can I remove or replace strings (not set) in my GridView and ListView?


Solution

  • Two ways that I know (now):

    Formatter

    Set nullDisplay of Formatter to something other than null. You can do this in global configuration or for the single GridView or DetailView.

    Globally (typically in config/web.php or <application>/config/main.php files):

    'components' => [
        ...
        'formatter' => [
            'class' => 'yii\i18n\Formatter',
            'nullDisplay' => '',
        ],
        ...
    ],
    

    In certain GridView (same with DetailView):

    <?= GridView::widget([
        'dataProvider' => $myProvider,
        'formatter' => ['class' => 'yii\i18n\Formatter','nullDisplay' => ''],
        'columns'      => [
            ...
        ],
    ]); ?>
    

    Set the value

    Probably not so elegant. In a certain GridView:

    <?= GridView::widget([
        'dataProvider' => $myProvider,
        'columns'      => [
            ...
            [
                'attribute' => 'some_attribute',
                'format'    => 'raw',
                'value'     => function (ModelClass $model) {
                    if ($model->some_attribute != null) {
                        return $model->some_attribute; 
                  //or: return Html::encode($model->some_attribute)
                    } else {
                        return '';
                    }
                },
            ],
            ...
        ],
    ]); ?>
    

    Or in a certain DetailView:

    <?= DetailView::widget([
        'model'      => $model,
        'attributes' => [
            ...
            [
                'attribute' => 'some_attribute',
                'value' => $model->some_attribute != null ? $model->some_attribute : '', 
          //or: 'value' => $model->some_attribute != null ? Html::encode($model->some_attribute) : '',
            ],
            ...
        ],
    ]) ?>
    

    Two hints

    If several approaches are used at the same time: setting the value (directly or by function) overrides the formatter configuration of the Grid/DetailView, and this in turn overrides a global formatter configuration.

    You can also define something different than an empty string. E.g. if bootstrap is used you may want to use \yii\bootstrap\Html::icon('question-sign') (or '<span class="glyphicon glyphicon-question-sign"></span>') to get a symbol for missing values.