/** * Creates a new Tour model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Tour(); $model->generateDefaultFields(); $modelsCustomField = $model->customFields; if ($model->load(Yii::$app->request->post())) { $model->created_at = time(); $modelsCustomField = Model::createMultiple(CustomField::classname()); Model::loadMultiple($modelsCustomField, Yii::$app->request->post()); // ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelsCustomField), ActiveForm::validate($model)); } // validate all models $valid = $model->validate(); $valid = Model::validateMultiple($modelsCustomField) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $model->save(false)) { foreach ($modelsCustomField as $modelCustomField) { $modelCustomField->tour_id = $model->id; if (!($flag = $modelCustomField->save(false))) { $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } } catch (Exception $e) { $transaction->rollBack(); } } } return $this->render('create', ['model' => $model, 'modelsCustomField' => empty($modelsCustomField) ? [new CustomField()] : $modelsCustomField]); }