我建议编写一个小部件来显示相关记录的链接列表。它是可重用的,防止在模型/控制器中生成 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,因为默认情况下内容呈现为纯文本以防止XSS攻击(html特殊字符被转义)。
您可以修改它以满足您的需要,这只是一个示例。