/** * Updates an existing Insumo 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); $modelsPresentacion = $model->presentacions; if ($model->load(Yii::$app->request->post()) && $model->save()) { $oldIDs = ArrayHelper::map($modelsPresentacion, 'id', 'id'); $modelsPresentacion = Model::createMultiple(Presentacion::className(), $modelsPresentacion); Model::loadMultiple($modelsPresentacion, Yii::$app->request->post()); $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPresentacion, 'id', 'id'))); // validate all models $valid = $model->validate(); $valid = Model::validateMultiple($modelsPresentacion) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $model->save(false)) { if (!empty($deletedIDs)) { Presentacion::deleteAll(['id' => $deletedIDs]); } foreach ($modelsPresentacion as $modelPresentacion) { $modelPresentacion->insumo_id = $model->id; if (!($flag = $modelPresentacion->save(false))) { $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); return $this->redirect(['index']); //return $this->redirect(['view', 'id' => $model->id]); } } catch (Exception $e) { $transaction->rollBack(); } } //return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('update', ['model' => $model, 'modelsPresentacion' => empty($modelsPresentacion) ? [new Presentacion()] : $modelsPresentacion]); } return $this->redirect(['index']); }