コード例 #1
0
 /**
  * Creates a new Tag model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Tag();
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         return $this->redirect(['view', 'id' => $model->id]);
     } else {
         return $this->render('createTag', ['model' => $model]);
     }
 }
コード例 #2
0
 /**
  * Updates an existing Blog model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     $items = [];
     foreach ($model->getTags()->all() as $item) {
         $items[] = $item->title;
     }
     $model->tagged = implode(', ', $items);
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         $tags = array_unique(preg_split('/\\s*,\\s*/u', preg_replace('/\\s+/u', ' ', is_array($model->tagged) ? implode(',', $model->tagged) : $model->tagged), -1, PREG_SPLIT_NO_EMPTY));
         $removed = array_diff($items, $tags);
         foreach (Tag::find()->where(['in', 'title', $removed])->all() as $removedItem) {
             BlogTag::deleteAll(['blog_id' => $model->id, 'tag_id' => $removedItem->id]);
             $removedItem->frequency--;
             $removedItem->save();
         }
         $added = array_diff($tags, $items);
         $rows = [];
         foreach ($added as $title) {
             $tag = Tag::findOne(['title' => $title]);
             if (!$tag) {
                 $tag = new Tag();
                 $tag->title = $title;
             }
             $tag->frequency++;
             if (!$tag->save()) {
                 Yii::error("Cannot save tag " . $tag->title . json_encode($tag->getErrors()));
                 continue;
             }
             $rows[] = [$model->id, $tag->id];
         }
         if (!empty($rows)) {
             $model->getDb()->createCommand()->batchInsert('{{%blog_tag}}', ['blog_id', 'tag_id'], $rows)->execute();
         }
         return $this->redirect(Yii::$app->request->referrer);
     } else {
         return $this->render('updateBlog', ['model' => $model]);
     }
 }