/** * 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]); } }
/** * Creates a new QuestionList model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $modelQuestionList = new QuestionList(); // добавляем в объект класса QuestionList данные, пришедние из формы if ($modelQuestionList->load(Yii::$app->request->post())) { // создаются $modelsQuestion = Model::createMultiple(Question::classname()); $modelsAnswerVariant = []; Model::loadMultiple($modelsQuestion, Yii::$app->request->post()); $valid = $modelQuestionList->validate(); $valid = Model::validateMultiple($modelsQuestion) && $valid; $postAnswerVariants = Yii::$app->request->post()['AnswerVariant']; if (isset($postAnswerVariants[0])) { foreach ($postAnswerVariants as $indexQuestion => $answers) { if ($modelsQuestion[$indexQuestion]->type === 'select_one') { foreach ($answers as $indexAnswer => $answer) { $data = []; $data['AnswerVariant'] = $answer; $modelAnswerVariant = new AnswerVariant(); $modelAnswerVariant->load($data); $modelsAnswerVariant[$indexQuestion][] = $modelAnswerVariant; } } } } if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $modelQuestionList->save(false)) { foreach ($modelsQuestion as $indexQuestion => $modelQuestion) { if (!($flag = $modelQuestion->save(false))) { $transaction->rollBack(); break; } else { $modelQuestion->link('questionLists', $modelQuestionList); } if (isset($modelsAnswerVariant[$indexQuestion]) && is_array($modelsAnswerVariant[$indexQuestion])) { foreach ($modelsAnswerVariant[$indexQuestion] as $modelAnswerVariant) { if (!$modelAnswerVariant->answer) { continue; } $modelAnswerVariant->question_id = $modelQuestion->id; if (!($flag = $modelAnswerVariant->save(false))) { break; } } } } } if ($flag) { $transaction->commit(); return $this->redirect(['view', 'id' => $modelQuestionList->id]); } else { $transaction->rollBack(); } } catch (Exception $e) { $transaction->rollBack(); } } } else { return $this->render('create', ['modelQuestionList' => $modelQuestionList, 'modelsQuestion' => empty($modelsQuestions) ? [new Question()] : $modelsQuestions, 'modelsAnswerVariant' => empty($modelsAnswerVariant) ? [[new AnswerVariant()]] : $modelsAnswerVariant]); } }