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]);
 }
Beispiel #2
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     if (!$this->post_id) {
         return '';
     }
     /* TODO: Посчитать количество добавлений в избранное и есть ли в избранном у текущего пользователя */
     $favorites = FavoritePosts::find()->where(['post_id' => $this->post_id])->asArray()->all();
     // количество добавлений статьи в избранное
     $options['favorites_num'] = count($favorites);
     // есть ли в избранном у текущего пользователя
     $inFavorite = false;
     if (!Yii::$app->user->isGuest) {
         foreach ($favorites as $fav) {
             if ($fav['user_id'] == Yii::$app->user->identity->getId()) {
                 $inFavorite = true;
             }
         }
     }
     $options['button_class'] = $inFavorite ? 'favorite_button_yellow' : 'favorite_button_grey';
     return $this->render('favorite', ['options' => $options, 'message' => $this->message]);
 }
Beispiel #3
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getFavoritePosts()
 {
     return $this->hasMany(FavoritePosts::className(), ['post_id' => 'id']);
 }