Exemple #1
0
 /**
  * Creates a new Po model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Po();
     $modelsPoItems = [new Poitem()];
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         $modelsPoItems = Model::createMultiple(Poitem::classname());
         Model::loadMultiple($modelsPoItems, Yii::$app->request->post());
         // ajax validation
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return ArrayHelper::merge(ActiveForm::validateMultiple($modelsPoItems), ActiveForm::validate($model));
         }
         // validate all models
         $valid = $model->validate();
         $valid = Model::validateMultiple($modelsPoItems) && $valid;
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $model->save(false)) {
                     foreach ($modelsPoItems as $modelPoItem) {
                         $modelPoItem->po_id = $model->id;
                         if (!($flag = $modelPoItem->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, 'modelsPoItems' => empty($modelsPoItems) ? [new Poitem()] : $modelsPoItems]);
 }