Beispiel #1
0
 /**
  * Добавление статьи в избранное
  *
  * @return string
  * @throws \Exception
  */
 public function actionFavorite()
 {
     $message = '';
     $postId = 0;
     if (!Yii::$app->request->get('post_id')) {
         return 'Ошибка';
     }
     if (!Yii::$app->user->isGuest) {
         $postId = (int) Yii::$app->request->get('post_id');
         $favorite = new FavoritePosts();
         $favorite->post_id = $postId;
         $favorite->user_id = Yii::$app->user->identity->getId();
         try {
             if ($favorite->save()) {
                 $message = 'Статья добавлена в избранное!';
             } else {
                 $err = $favorite->errors;
                 $message = current($err)[0];
             }
         } catch (IntegrityException $e) {
             if (strpos($e->errorInfo[2], 'foreign key')) {
                 $message = 'Ошибка. Неверный ID статьи';
             }
         }
     } else {
         $message = 'Добавлять статьи в избранное могут только зарегистрированные пользователи';
     }
     return FavoriteWidget::widget(['post_id' => $postId, 'message' => $message]);
 }