Exemple #1
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     $linkTags = function ($event) {
         if ($this->tagIds === null) {
             return;
         }
         if (!is_array($this->tagIds)) {
             $this->tagIds = [];
         }
         $whereIds = $models = $newTagIds = [];
         foreach ($this->tagIds as $tagId) {
             if (empty($tagId)) {
                 continue;
             }
             if (preg_match("/^\\d+\$/", $tagId)) {
                 $whereIds[] = $tagId;
                 continue;
             }
             // если tagId не число, то значит надо создать новый тег
             if (!($tag = Tag::findOne(['name' => $tagId]))) {
                 $tag = new Tag();
                 $tag->name = $tagId;
                 if (!$tag->save()) {
                     continue;
                 }
             }
             $newTagIds[] = $tag->id;
             $models[] = $tag;
         }
         $this->unlinkAll('tags', true);
         if ($whereIds) {
             $models = array_merge($models, Tag::find()->where(['id' => $whereIds])->all());
         }
         foreach ($models as $model) {
             $this->link('tags', $model);
         }
         // что бы после сохранения в значение были новые теги
         $this->tagIds = array_merge($whereIds, $newTagIds);
     };
     $this->on(static::EVENT_AFTER_INSERT, $linkTags);
     $this->on(static::EVENT_AFTER_UPDATE, $linkTags);
 }