/** * @param $name * @return QaUser|bool */ public function createUser($name) { $newUser = new QaUser(); $newUser->username = $name; if ($newUser->save()) { return $newUser; } return false; }
/** * User Relation * @return \yii\db\ActiveQueryInterface */ public function getUser() { return $this->hasOne(\app\modules\qa\models\QaUser::className(), ['id' => 'user_id']); }
/** * @param $id * @return string|Response */ public function actionAnswer($id) { $name = ''; if (isset($_POST['QaUser']['username'])) { $name = $_POST['QaUser']['username']; } $model = new Answer(['question_id' => $id]); $userModel = new QaUser(); /** @var Question $question */ $question = $model->question; if (!$question) { $this->notFoundException(); } if ($model->load($_POST) && $userModel->load($_POST)) { $valid = $model->validate(); $valid = $userModel->validate() && $valid; if (!$valid) { return $this->render('answer', compact(['model', 'question', 'userModel'])); } } $user = $userModel->find()->where(['username' => $name])->one(); if (!$user) { $user = $userModel->createUser($name); } if ($model->load($_POST)) { $model->user_id = $user->id; } if ($model->save()) { Yii::$app->session->setFlash('answerFormSubmitted'); return $this->redirect(Url::to(['view', 'id' => $question->id, 'alias' => $question->alias])); } else { return $this->render('answer', compact('model', 'question', 'userModel')); } }