Search code examples
yiiyii2detailview

Filter empty values in DetailView


Is there an easy way to force DetailView in Yii2 to ignore these fields in its attributes list, that for particular model are empty?

Or the only way is to define every attribute on attributes list with own function and filter empty fields inside it (sound like a little bit of madness)?

Edit: I thought, that this is pretty self-explanatory, but it turned out, it isn't. So, basically, I want to force DetailView to ignore (not render) rows for these elements of attributes list, that have empty (null, empty string) values in corresponding model and thus would result in rendering empty table cell:

enter image description here


Solution

  • You can define template parameter of DetailView widget as a callback function with following signature function ($attribute, $index, $widget) and this callback will be called for each attribute, so you can define desired rendering for your rows:

    DetailView::widget([
        'model' => $model,
        'template' => function($attribute, $index, $widget){
            //your code for rendering here. e.g.
            if($attribute['value'])
            {
                return "<tr><th>{$attribute['label']}</th><td>{$attribute['value']}</td></tr>";
            }
        },
        //other parameters
    ]);