Exemplo n.º 1
0
 /**
  * @return string
  *
  * Отображает чистую форму для заполнения со списком вопросов
  */
 public function actionCreate($id)
 {
     $modelAnswerList = $this->findAnswerListModel($id);
     if (!$this->getAccessToOffice($modelAnswerList->do_id)) {
         Yii::$app->getResponse()->redirect(Url::toRoute(['write-test/index']));
     }
     if ($modelAnswerList->status !== 'clear') {
         Yii::$app->getResponse()->redirect(Url::toRoute(['write-test/update', 'id' => $modelAnswerList->id]));
     }
     $modelQuestionList = $modelAnswerList->questionList;
     $modelsQuestion = $modelQuestionList->questions;
     // если форма отправлена.
     if ($postData = Yii::$app->request->post()) {
         $modelAnswerList->status = 'answered';
         $modelsAnswer = Model::createMultiple(Answer::classname(), [], $scenario = ['scenario' => 'create']);
         Model::loadMultiple($modelsAnswer, $postData);
         $valid = $modelQuestionList->validate();
         foreach ($modelsAnswer as $indexModelAnswer => $modelAnswer) {
             $modelAnswer->profile_id = Yii::$app->user->identity->username;
             $valid = $modelAnswer->validate() && $valid;
         }
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 $flag = false;
                 if ($modelAnswerList->save()) {
                     foreach ($modelsAnswer as $indexModelAnswer => $modelAnswer) {
                         if (!($flag = $modelAnswer->save(false))) {
                             $transaction->rollBack();
                             break;
                         }
                     }
                 }
                 if ($flag) {
                     $transaction->commit();
                     return $this->redirect(['view', 'id' => $modelAnswerList->id]);
                 } else {
                     $transaction->rollBack();
                 }
             } catch (Exception $e) {
                 $transaction->rollBack();
             }
         }
     }
     return $this->render('create', ['modelQuestionList' => $modelQuestionList, 'modelAnswerList' => $modelAnswerList, 'modelsQuestion' => $modelsQuestion]);
 }