php - Yii2: has_many gridview and detailview -


i'm going use 1st normalization form in yii2 project, i've added table
| id | post_id | tag_id |
and when i'm posts model i've writed this:

public function gettags() {     return $this->hasmany(posttags::classname(), ['post_id' => 'id']); } 

in view widget i've added 'tags.tag_id', shows no data.
there way show tags in detailview , gridview widgets?

may be, can write "group_concat" somewhere?

i'd recommend write widget displaying links list of related records. it's reusable, prevents html generation in model / controller, reduces amount of code in view.

<?php  namespace common\widgets;  use yii\base\widget; use yii\helpers\html;  /**  * widget display list of links related models  */ class relatedlist extends widget {     /**      * @var \yii\db\activerecord[] related models      */     public $models = [];      /**      * @var string base build text content of link.      * should specify attribute name. in case of dynamic generation ('getfullname()') should specify 'fullname'.      */     public $linkcontentbase = 'name';      /**      * @var string route build url related model      */     public $viewroute;      /**      * @inheritdoc      */     public function run()     {         if (!$this->models) {             return null;         }          $items = [];         foreach ($this->models $model) {             $items[] = html::a($model->{$this->linkcontentbase}, [$this->viewroute, 'id' => $model->id]);         }          return html::ul($items, [             'class' => 'list-unstyled',             'encode' => false,         ]);     } } 

here examples (assuming tag name stored in name column).

usage in gridview:

[     'attribute' => 'tags',     'format' => 'raw',     'value' => function ($model) {         /* @var $model common\models\post */         return relatedlist::widget([             'models' => $model->tags,             'viewroute' => '/tags/view',         ]);     }, ], 

usage in detailview:

/* @var $model common\models\post */  ...  [     'attribute' => 'tags',     'format' => 'raw',     'value' => relatedlist::widget([         'models' => $model->tags,         'viewroute' => '/tags/view',     ]),         ], 

don't forget set format raw, because default content rendered plain text prevent xss attacks (html special characters escaped).

you can modify fit needs, example.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -