示例#1
0
 /**
  * Updates an existing Po model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     //$modelsPoitems = $model->poitems; oh that error !!!
     $modelsPoitems = Poitem::find()->where(['po_id' => $id])->all();
     //it ture! :D
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         $oldIDs = ArrayHelper::map($modelsPoitems, 'id', 'id');
         $modelsPoitems = Model::createMultiple(Poitem::classname(), $modelsPoitems);
         Model::loadMultiple($modelsPoitems, Yii::$app->request->post());
         $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPoitems, 'id', 'id')));
         // validate all models
         $valid = $model->validate();
         $valid = Model::validateMultiple($modelsPoitems) && $valid;
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $model->save(false)) {
                     if (!empty($deletedIDs)) {
                         Poitem::deleteAll(['id' => $deletedIDs]);
                     }
                     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();
             }
         }
     } else {
         return $this->render('update', ['model' => $model, 'modelsPoitems' => empty($modelsPoitems) ? [new Poitem()] : $modelsPoitems]);
     }
 }