コード例 #1
0
 /**
  * Creates a new Parameter model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $models = [new Parameter()];
     if (Yii::$app->request->post()) {
         $models = Model::createMultiple(Parameter::classname());
         Model::loadMultiple($models, Yii::$app->request->post());
         // ajax validation
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return ActiveForm::validateMultiple($models);
         }
         // validate all models
         $valid = Model::validateMultiple($models);
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 $flag = true;
                 foreach ($models as $model) {
                     if (!($flag = $model->save(false))) {
                         $transaction->rollBack();
                         break;
                     }
                 }
                 if ($flag) {
                     $transaction->commit();
                     Yii::$app->session->setFlash('alert', ['options' => ['class' => 'alert-success'], 'body' => Yii::t('backend', 'Your data has been successfully saved')]);
                     return $this->redirect(['index']);
                 }
             } catch (Exception $e) {
                 $transaction->rollBack();
                 Yii::$app->session->setFlash('alert', ['options' => ['class' => 'alert-danger'], 'body' => Yii::t('backend', 'Your data can\'t be saved')]);
                 return $this->redirect(['index']);
             }
         }
     }
     return $this->render('create', ['models' => empty($models) ? [new Parameter()] : $models]);
 }