示例#1
0
 /**
  * Creates a new Sale model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Sale();
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         return $this->redirect(['view', 'id' => $model->id]);
     } else {
         return $this->render('create', ['model' => $model]);
     }
 }
示例#2
0
 /**
  * Creates a new Sale model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Sale();
     $modelDetails = null;
     if ($model->load(Yii::$app->request->post())) {
         $modelDetails = Model::createMultiple(SaleDetail::classname());
         Model::loadMultiple($modelDetails, Yii::$app->request->post());
         // validate all models
         $valid = $model->validate() & Model::validateMultiple($modelDetails);
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $model->save(false)) {
                     foreach ($modelDetails as $modelDetail) {
                         $modelDetail->sale_id = $model->id;
                         if ($flag = $modelDetail->save(false)) {
                             $item = Item::findOne($modelDetail->item_id);
                             $item->stock -= $modelDetail->quantity;
                             $flag = $item->save();
                         }
                         if (!$flag) {
                             $transaction->rollBack();
                             break;
                         }
                     }
                 }
                 if ($flag) {
                     $transaction->commit();
                     return $this->redirect(['index']);
                 }
             } catch (Exception $e) {
                 $transaction->rollBack();
             }
         }
     }
     return $this->render('create', ['model' => $model, 'modelDetails' => empty($modelDetails) ? [new SaleDetail()] : $modelDetails]);
 }