Ejemplo n.º 1
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getPoItems()
 {
     return $this->hasMany(PoItem::className(), ['po_id' => 'id']);
 }
Ejemplo n.º 2
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);
     $modelsPoItem = $model->poItems;
     if ($model->load(Yii::$app->request->post())) {
         $oldIDs = ArrayHelper::map($modelsPoItem, 'id', 'id');
         $modelsPoItem = Model::createMultiple(PoItem::className(), $modelsPoItem);
         Model::loadMultiple($modelsPoItem, Yii::$app->request->post());
         $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPoItem, 'id', 'id')));
         // validate all models
         $valid = $model->validate();
         $valid = Model::validateMultiple($modelsPoItem) && $valid;
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $model->save(false)) {
                     if (!empty($deletedIDs)) {
                         PoItem::deleteAll(['id' => $deletedIDs]);
                     }
                     foreach ($modelsPoItem 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, 'modelsPoItem' => empty($modelsPoItem) ? [new PoItem()] : $modelsPoItem]);
     }
 }