我建議編寫一個小部件來顯示相關記錄的鏈接列表。它可重複使用,防止模型/控制器中的HTML生成,減少視圖中的代碼量。
<?php
namespace common\widgets;
use yii\base\Widget;
use yii\helpers\Html;
/**
* Widget for display list of links to related models
*/
class RelatedList extends Widget
{
/**
* @var \yii\db\ActiveRecord[] Related models
*/
public $models = [];
/**
* @var string Base to build text content of the link.
* You should specify attribute name. In case of dynamic generation ('getFullName()') you should specify just 'fullName'.
*/
public $linkContentBase = 'name';
/**
* @var string Route to build url to related model
*/
public $viewRoute;
/**
* @inheritdoc
*/
public function run()
{
if (!$this->models) {
return null;
}
$items = [];
foreach ($this->models as $model) {
$items[] = Html::a($model->{$this->linkContentBase}, [$this->viewRoute, 'id' => $model->id]);
}
return Html::ul($items, [
'class' => 'list-unstyled',
'encode' => false,
]);
}
}
下面是一些示例(假設標記名稱存儲在name
列中)。
用法在GridView
:
[
'attribute' => 'tags',
'format' => 'raw',
'value' => function ($model) {
/* @var $model common\models\Post */
return RelatedList::widget([
'models' => $model->tags,
'viewRoute' => '/tags/view',
]);
},
],
用法在DetailView
:
/* @var $model common\models\Post */
...
[
'attribute' => 'tags',
'format' => 'raw',
'value' => RelatedList::widget([
'models' => $model->tags,
'viewRoute' => '/tags/view',
]),
],
不要忘記設置格式raw
,因爲默認情況下的內容呈現爲純文本,以防止跨站腳本攻擊(HTML特殊字符被轉義)。
您可以修改它以符合您的需求,這僅僅是一個例子。
我發現了這個問題。我沒有添加** joinWith **到DataProvider查詢 –