Yii2 basic gridview just header and values

安稳与你 提交于 2019-12-24 06:49:48

问题


I would like to show data of a joined query... (Controller):

$znw_a = Znw::find()->withA()->where(['znw.id' => $zg_id])->one();
...
return $this->render('create', [
    ...
    'znw_a' => $znw_a,

...like a very basic gridview, without pager, summary, etc, only the pure header with the data. The main idea is to show it like if it was a detailview simply transposed, so that I see data from left to right instead of top to bottom, so like a simple Excel table for example.

Is there such a simple widget like this in yii? Because GridView is not working like this, and before I'm trying to adjust my query in order to match the criteria of Gridview, maybe someone can give me a tip and I can achieve what I want easier. Can you please point me to the right direction? Many thanks!


回答1:


Extend DetailView for this one and use your class instead. Something like (assuming basic project template):

namespace app\widgets;

use yii\widgets\DetailView;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

class MyDetailView extends DetailView
{
    public $template = '<td>{value}</td>';
    public $headerTemplate = '<th>{label}</th>';

    public function run()
    {
        $rows = [];
        $headers = [];
        $i = 0;
        foreach ($this->attributes as $attribute) {
            list($row, $header) = $this->renderAttribute($attribute, $i++);
            $rows[] = $row;
            $headers[] = $header;
        }

        $options = $this->options;
        $tag = ArrayHelper::remove($options, 'tag', 'table');
        $topRow = Html::tag('tr', implode("\n", $headers));
        $dataRow = Html::tag('tr', implode("\n", $rows));
        echo Html::tag($tag, $topRow . $dataRow, $options);
    }

    protected function renderAttribute($attribute, $index)
    {
        if (is_string($this->template)) {
            $row = strtr($this->template, [
                '{value}' => $this->formatter->format($attribute['value'], $attribute['format']),
            ]);
        } else {
            $row = call_user_func($this->template, $attribute, $index, $this);
        }
        if (is_string($this->headerTemplate)) {
            $header = strtr($this->headerTemplate, [
                '{label}' => $attribute['label'],
            ]);
        } else {
            $header = call_user_func($this->headerTemplate, $attribute, $index, $this);
        }
        return [$row, $header];
    }
}

save it to /widgets/MyDetailView.php

Use it with

use app\widgets\MyDetailView;

<?= MyDetailView::widget([
    // ...
]) ?>


来源:https://stackoverflow.com/questions/43109629/yii2-basic-gridview-just-header-and-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!