Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 664
trejder Avatar asked Jan 08 '23 01:01

trejder


2 Answers

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
]);
like image 79
Tony Avatar answered Jan 22 '23 03:01

Tony


Would something like this work better? It preserves some of the niceties like: updated_at:datetime, which with one of the solutions above will just show the underlying value, not a converted value.

<?= DetailView::widget([
    'model' => $model,

    'attributes' => [
        'id',
        [
            'attribute' => 'my_attribute',
            'visible' => !empty($model->my_attribute)
        ],
    ]
]);
like image 41
johnsnails Avatar answered Jan 22 '23 04:01

johnsnails