/** * @return \yii\db\ActiveQuery */ public function getFormConfirmation() { return $this->hasOne(FormConfirmation::className(), ['form_id' => 'id'])->inverseOf('form'); }
/** * Create form * * @return array * @throws Exception * @throws \yii\db\Exception */ public function actionCreateForm() { if (Yii::$app->request->isAjax) { // Response fornat Yii::$app->response->format = Response::FORMAT_JSON; // Extract FormBuilder data from post request $post = Yii::$app->request->post(); $data = ['FormBuilder' => Json::decode($post['FormBuilder'], true)]; $formBuilder = new FormBuilder(); // Flags variables $success = false; $id = false; $message = ''; $code = 0; // Form Builder Validation if ($formBuilder->load($data) && $formBuilder->validate()) { // Save data in single transaction $transaction = Form::getDb()->beginTransaction(); try { // Parse html form fields to array $formDOM = new FormDOM(); // If two elements has same id, throw a exception $formDOM->loadHTML($data['FormBuilder']['html']); $formDOM->loadXpath(); $formDOM->loadFields(); // Filter reCaptcha component $reCaptchaComponent = ArrayHelper::filter(ArrayHelper::getValue($data, 'FormBuilder.data.initForm'), 'recaptcha', 'name'); // Populate Form Model and Save $postForm = ['Form' => ['name' => ArrayHelper::getValue($data, 'FormBuilder.data.settings.name'), 'language' => Yii::$app->language, 'recaptcha' => count($reCaptchaComponent) > 0 ? 1 : 0]]; // Save Form Model $formModel = new Form(); if ($formModel->load($postForm) && $formModel->save()) { // Set form id $id = $formModel->primaryKey; } else { throw new Exception(Yii::t('app', 'Error saving data'), 1); } // Post Form Data $postFormData = ['FormData' => ['form_id' => $id, 'builder' => Json::htmlEncode(ArrayHelper::getValue($data, 'FormBuilder.data')), 'fields' => $formDOM->getFieldsAsJSON(), 'html' => Html::encode(ArrayHelper::getValue($data, 'FormBuilder.html')), 'height' => ArrayHelper::getValue($data, 'FormBuilder.data.height')]]; // Populate FormData Model and Save $formDataModel = new FormData(); if (!$formDataModel->load($postFormData) || !$formDataModel->save()) { throw new Exception(Yii::t('app', 'Error saving data'), 2); } // Save FormUI Model $formUIModel = new FormUI(); $formUIModel->link('form', $formModel); // Save FormConfirmation Model $formConfirmationModel = new FormConfirmation(); $formConfirmationModel->link('form', $formModel); // Save FormEmail Model $formEmailModel = new FormEmail(); $formEmailModel->link('form', $formModel); $transaction->commit(); // Change success flag and message $success = true; $message = Yii::t("app", "The form has been successfully created."); } catch (Exception $e) { // Rolls back the transaction $transaction->rollBack(); // Rethrow the exception // throw $e; $message = $e->getMessage(); $code = $e->getCode(); } } // Response to Client $res = array('success' => $success, 'id' => $id, 'action' => 'create', 'message' => $message, 'code' => $code); return $res; } return ''; }