コード例 #1
0
 /**
  * Updates an existing Question model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @param integer $list_id
  * @return mixed
  */
 public function actionUpdate($id, $list_id)
 {
     // Проверяем можем ли изменить вопрос.
     if (!$this->canCreateQuestion($list_id)) {
         return $this->render('question_list_is_lock', ['modelQuestionList' => QuestionList::findOne($list_id), 'action' => 'update']);
     }
     $model = $this->findModel($id);
     $post = Yii::$app->request->post();
     //$model->answerVariants
     //если данные загрузились в объект вопроса и он валиден
     if ($model->load($post) && ($valid = $model->validate())) {
         $transaction = \Yii::$app->db->beginTransaction();
         // Если сохранили успешно объек вопроса
         if ($model->save()) {
             //Если для этого типа нужно сохранять опции
             switch ($model->type) {
                 case 'select_one':
                 case 'select_multiple':
                 case 'radio':
                     $modelsAnswerVariants = [];
                     $deletedAnswerVariantsIDs = array_values(ArrayHelper::map($model->answerVariants, 'id', 'id'));
                     if ($post['AnswerVariant']) {
                         foreach ($post['AnswerVariant'] as $av) {
                             $m = new AnswerVariant();
                             $m->id = $av['id'];
                             $modelsAnswerVariants[] = $m;
                         }
                     }
                     Model::loadMultiple($modelsAnswerVariants, $post);
                     if (!empty($deletedAnswerVariantsIDs)) {
                         AnswerVariant::deleteAll(['id' => $deletedAnswerVariantsIDs]);
                     }
                     foreach ($modelsAnswerVariants as $answerVariantModel) {
                         $answerVariantModel->question_id = $model->id;
                         $valid = $answerVariantModel->save();
                     }
                     if ($valid) {
                         $transaction->commit();
                         return $this->redirect(['view', 'id' => $model->id, 'list_id' => $list_id]);
                     } else {
                         $transaction->rollBack();
                         return $this->render('update', ['model' => $model, 'list_id' => $list_id]);
                     }
                     break;
                 case 'checkbox':
                     $answerVariantModel = $model->answerVariants[0];
                     // если не переданы кол-во балов при установке чек-бокса
                     if (!(int) $post['checkboxUpScores']) {
                         //но они были ранее
                         if ($answerVariantModel) {
                             $answerVariantModel->delete();
                         }
                         break;
                     }
                     if (!$answerVariantModel) {
                         $answerVariantModel = new AnswerVariant();
                         $answerVariantModel->answer = '1';
                         $answerVariantModel->question_id = $model->id;
                     }
                     //а если переданы, то заменяем
                     $answerVariantModel->scores = (int) $post['checkboxUpScores'];
                     $valid = $answerVariantModel->save();
                     break;
                 default:
                     //На тот случай, если сменили тип поля с ВЫБОР ИЗ ВАРИАНТОВ на ТЕКСТ, удаляем варианты ответа
                     AnswerVariant::deleteAll(['id' => array_values(ArrayHelper::map($model->answerVariants, 'id', 'id'))]);
             }
         } else {
             $transaction->rollBack();
         }
         if ($valid) {
             $transaction->commit();
             return $this->redirect(['view', 'id' => $model->id, 'list_id' => $list_id]);
         } else {
             $transaction->rollBack();
             return $this->render('create', ['model' => $model, 'list_id' => $list_id]);
         }
     } else {
         return $this->render('update', ['model' => $model, 'list_id' => $list_id]);
     }
 }
コード例 #2
0
 /**
  * @return string
  *
  * Отображает чистую форму для заполнения со списком вопросов
  */
 public function actionUpdate($id)
 {
     $modelAnswerList = $this->findAnswerListModel($id);
     $modelAnswerList->scenario = 'write-test';
     $modelQuestionList = $modelAnswerList->questionList;
     $modelsQuestion = $modelQuestionList->questions;
     $modelsAnswer = $modelAnswerList->answers;
     // если форма отправлена.
     if ($postData = Yii::$app->request->post()) {
         $valid = $modelQuestionList->validate();
         $answerIds = ArrayHelper::getColumn($postData['Answer'], 'id');
         $modelsAnswer = Answer::findAll($answerIds);
         Model::loadMultiple($modelsAnswer, $postData);
         //если был удален один вопрос, на который ранее отвечали
         $oldAnswerIDs = ArrayHelper::map($modelAnswerList->answers, 'id', 'id');
         $deletedAnswerIDs = array_diff($oldAnswerIDs, array_filter($answerIds));
         // если был добавлен еще один вопрос, то создадим пустой и добавим
         foreach ($postData['Answer'] as $answer) {
             if (!$answer['id']) {
                 $modelAnswerVariant = new Answer();
                 $modelAnswerVariant->load(['Answer' => $answer]);
                 $modelsAnswer[] = $modelAnswerVariant;
             }
         }
         // сумма очков
         $sumScores = 0;
         $groupsOfModelsAnswerVariants = $this->getAllAnswerVariantsGroupByQuestionId($modelAnswerList->question_list_id);
         foreach ($modelsAnswer as $modelAnswer) {
             $modelAnswer->question_list_id = $modelAnswerList->question_list_id;
             $modelAnswer->answer_list_id = $modelAnswerList->id;
             $valid = $modelAnswer->validate();
             if (!$valid) {
                 break;
             }
             if (isset($groupsOfModelsAnswerVariants[$modelAnswer->question_id]) && isset($groupsOfModelsAnswerVariants[$modelAnswer->question_id][$modelAnswer->answer])) {
                 $score = $groupsOfModelsAnswerVariants[$modelAnswer->question_id][$modelAnswer->answer]->scores;
                 $sumScores += $score;
             }
         }
         $transaction = \Yii::$app->db->beginTransaction();
         if ($valid) {
             try {
                 $flag = false;
                 $modelAnswerList->scores = $sumScores;
                 if ($modelAnswerList->save()) {
                     foreach ($modelsAnswer as $indexModelAnswer => $modelAnswer) {
                         if (!($flag = $modelAnswer->save(false))) {
                             $transaction->rollBack();
                             break;
                         }
                     }
                 }
                 // удаляем вопросы, которые могли быть удалены в конструкторе
                 if ($deletedAnswerIDs) {
                     $del = Answer::findAll(array_values($deletedAnswerIDs));
                     foreach ($del as $model) {
                         $model->delete();
                     }
                 }
                 if ($flag) {
                     $transaction->commit();
                     return $this->redirect(['view', 'id' => $modelAnswerList->id]);
                 } else {
                     $transaction->rollBack();
                 }
             } catch (Exception $e) {
                 $transaction->rollBack();
             }
         }
     }
     return $this->render('update', ['modelQuestionList' => $modelQuestionList, 'modelAnswerList' => $modelAnswerList, 'modelsQuestion' => $modelsQuestion, 'modelsAnswer' => $modelsAnswer]);
 }
コード例 #3
0
 /**
  * Updates an existing QuestionList model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $modelQuestionList = $this->findModel($id);
     $modelsQuestion = $modelQuestionList->questions;
     $modelsAnswerVariant = [];
     $oldAnswerVariants = [];
     if (!empty($modelsQuestion)) {
         foreach ($modelsQuestion as $indexQuestion => $modelQuestion) {
             $answerVariants = $modelQuestion->answerVariants;
             $modelsAnswerVariant[$indexQuestion] = $answerVariants;
             $oldAnswerVariants = ArrayHelper::merge(ArrayHelper::index($answerVariants, 'id'), $oldAnswerVariants);
         }
     }
     if ($modelQuestionList->load(Yii::$app->request->post())) {
         $oldQuestionIDs = ArrayHelper::map($modelsQuestion, 'id', 'id');
         $modelsQuestion = [];
         $postQuestionData = Yii::$app->request->post()['Question'];
         if ($postQuestionData) {
             foreach ($postQuestionData as $q) {
                 $question = new Question();
                 if ($q['id']) {
                     $actualIds[$q['id']] = $q['id'];
                     $question->id = $q['id'];
                 }
                 $modelsQuestion[] = $question;
             }
         }
         Model::loadMultiple($modelsQuestion, Yii::$app->request->post());
         $deletedQuestionIDs = array_diff($oldQuestionIDs, array_filter(ArrayHelper::map($modelsQuestion, 'id', 'id')));
         $valid = $modelQuestionList->validate();
         $valid = Model::validateMultiple($modelsQuestion) && $valid;
         $answerVariantsIDs = [];
         $postAnswersData = Yii::$app->request->post()['AnswerVariant'];
         if (isset($postAnswersData[0])) {
             foreach ($postAnswersData as $indexQuestion => $answerVariants) {
                 $answerVariantsIDs = ArrayHelper::merge($answerVariantsIDs, array_filter(ArrayHelper::getColumn($answerVariants, 'id')));
                 foreach ($answerVariants as $indexAnswerVariant => $answerVariant) {
                     if (!$answerVariant['answer']) {
                         continue;
                     }
                     $data['AnswerVariant'] = $answerVariant;
                     $modelAnswerVariant = isset($answerVariant['id']) && isset($oldAnswerVariants[$answerVariant['id']]) ? $oldAnswerVariants[$answerVariant['id']] : new AnswerVariant();
                     $modelAnswerVariant->load($data);
                     $modelsAnswerVariant[$indexQuestion][$indexAnswerVariant] = $modelAnswerVariant;
                     $valid = $modelAnswerVariant->validate();
                 }
             }
         }
         $oldAnswerVariantsIDs = ArrayHelper::getColumn($oldAnswerVariants, 'id');
         $deletedAnswerVariantsIDs = array_diff($oldAnswerVariantsIDs, $answerVariantsIDs);
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $modelQuestionList->save(false)) {
                     if (!empty($deletedAnswerVariantsIDs)) {
                         AnswerVariant::deleteAll(['id' => $deletedAnswerVariantsIDs]);
                     }
                     if (!empty($deletedQuestionIDs)) {
                         foreach ($deletedQuestionIDs as $q_id) {
                             Question::findOne($q_id)->unlink('questionLists', $modelQuestionList);
                             Question::findOne($q_id)->delete();
                         }
                     }
                     foreach ($modelsQuestion as $indexQuestion => $modelQuestion) {
                         if ($modelQuestion->id) {
                             $model = Question::findOne($modelQuestion->id);
                             $data = $modelQuestion->toArray();
                             if ($model) {
                                 $model->attributes = $data;
                                 $modelQuestion = $model;
                             }
                         }
                         if (!($flag = $modelQuestion->save())) {
                             $transaction->rollBack();
                             break;
                         }
                         if (isset($modelsAnswerVariant[$indexQuestion]) && is_array($modelsAnswerVariant[$indexQuestion])) {
                             foreach ($modelsAnswerVariant[$indexQuestion] as $indexAnswerVariant => $modelAnswerVariant) {
                                 if ($modelsQuestion[$indexQuestion]->type !== 'select_one') {
                                     $modelAnswerVariant->delete();
                                 } else {
                                     $modelAnswerVariant->question_id = $modelQuestion->id;
                                     if (!($flag = $modelAnswerVariant->save(false))) {
                                         break;
                                     }
                                 }
                             }
                         }
                         if (!$actualIds[$modelQuestion->id]) {
                             $modelQuestion->link('questionLists', $modelQuestionList);
                         }
                     }
                 }
                 if ($flag) {
                     $transaction->commit();
                     return $this->redirect(['view', 'id' => $modelQuestionList->id]);
                 }
             } catch (Exception $e) {
                 $transaction->rollBack();
             }
         }
     }
     return $this->render('update', ['modelQuestionList' => $modelQuestionList, 'modelsQuestion' => empty($modelsQuestion) ? [new Question()] : $modelsQuestion, 'modelsAnswerVariant' => empty($modelsAnswerVariant) ? [[new AnswerVariant()]] : $modelsAnswerVariant]);
 }
コード例 #4
0
 /**
  * @inheritdoc
  */
 public function scenarios()
 {
     // bypass scenarios() implementation in the parent class
     return Model::scenarios();
 }