public function actionRemove() { $postData = \Yii::$app->request->post(); $likeModel = Like::find()->where(['user_id' => \Yii::$app->user->getId(), 'model' => $postData['model'], 'item_id' => $postData['itemId']])->one(); \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; // небольшая проверка на случай если уже удалено из модального окна или на другой вкладке if ($likeModel) { // удаляем if ($likeModel->delete()) { return ['response' => true, 'url' => Url::toRoute('/like/element/add'), 'totalCount' => Like::find()->where(['model' => $postData['model'], 'item_id' => $postData['itemId']])->count()]; } // если уже удалено ранее } else { return ['response' => true, 'url' => Url::toRoute('/like/element/add'), 'totalCount' => Like::find()->where(['model' => $postData['model'], 'item_id' => $postData['itemId']])->count()]; } return ['response' => false]; }
public function run() { if (!is_object($this->model)) { return false; } $action = 'add'; $url = '/like/element/add'; $model = $this->model; $totalCount = Like::find()->where(['model' => $model::className(), 'item_id' => $model->id])->count(); $textTemplate = $this->text . ' ' . $totalCount; $currentUserId = \Yii::$app->user->getId(); if ($currentUserId === $model->user_id) { return Html::tag($this->htmlTag, $textTemplate, ['class' => 'hal-like-button-my-likes', 'data-role' => 'hal_like_button_my_likes']); } $elementModel = Like::find()->where(['user_id' => $currentUserId, 'model' => $model::className(), 'item_id' => $model->id])->one(); if ($elementModel) { $textTemplate = $this->text . ' ' . $totalCount; $this->cssClass .= ' ' . $this->cssClassInList; $action = 'remove'; $url = '/like/element/remove'; } return Html::tag($this->htmlTag, $textTemplate, ['class' => $this->cssClass, 'data-role' => 'hal_like_button', 'data-url' => Url::toRoute($url), 'data-action' => $action, 'data-item-id' => $model->id, 'data-model' => $model::className()]); }