/** * Creates a new Price model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreateByPo($id) { if (($purchase = Purchase::findOne($id)) === null) { throw new NotFoundHttpException('The requested page does not exist.'); } $products = []; foreach ($purchase->getPurchaseDtls()->with('product.category')->all() as $detail) { $product = new ProductPrice(['id' => $detail->product_id, 'name' => $detail->product->name, 'category' => $detail->product->category->name, 'price' => $detail->price]); $products[$detail->product_id] = $product; } if (ProductPrice::loadMultiple($products, Yii::$app->request->post()) && ProductPrice::validateMultiple($products)) { $transaction = Yii::$app->db->beginTransaction(); try { $success = true; foreach ($products as $product) { if (!$product->save(false)) { $success = false; break; } } if ($success) { $transaction->commit(); return $this->redirect(['list-po']); } else { $transaction->rollBack(); } } catch (\Exception $exc) { $transaction->rollBack(); throw $exc; } } return $this->render('create_by_po', ['purchase' => $purchase, 'products' => $products, 'categories' => PriceCategory::find()->all()]); }
/** * Finds the Purchase model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Purchase the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Purchase::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }