public function save($validate = true) { if ($this->validate($validate) && !Yii::$app->cart->isEmpty) { $transaction = Yii::$app->db->beginTransaction(); $this->productOrder->attributes = ['user_id' => Yii::$app->user->identity->id, 'address' => $this->address, 'contact' => $this->contact, 'payment' => $this->payment, 'shipment' => $this->shipment, 'total_price' => Yii::$app->cart->cost, 'status' => ProductOrder::STATUS_CREATED]; if (!$this->productOrder->save()) { return false; } foreach (Yii::$app->cart->positions as $productInCart) { $productOrderCompose = new ProductOrderCompose(); $productOrderCompose->attributes = ['order_id' => $this->productOrder->id, 'user_id' => Yii::$app->user->identity->id, 'product_id' => $productInCart->id, 'product_attribute_option_ids' => ProductInCart::getSerializedAttributeAssignments($productInCart->attributeAssignments), 'product_count' => $productInCart->quantity, 'settlement_price' => $productInCart->cost]; if (!$productOrderCompose->save(true)) { return false; } } $transaction->commit(); Yii::$app->cart->removeAll(); return true; } return false; }
public function actionAddToCart() { $productId = Yii::$app->request->post('productId', false); $quantity = abs((int) Yii::$app->request->post('quantity', false)); $attributeAssignments = []; foreach (Yii::$app->request->post('attributeAssignments', []) as $attributeAssignment) { $attributeId = ArrayHelper::getValue($attributeAssignment, 'attributeId'); $attributeOption = trim(ArrayHelper::getValue($attributeAssignment, 'attributeOption')); $productAttribute = ProductAttribute::findOne($attributeId); if (!$productAttribute->isValidOption($attributeOption)) { continue; } $attributeAssignments[] = ['attribute_id' => $attributeId, 'attribute_option' => $attributeOption]; } $productInCart = ProductInCart::findOne($productId); $productInCart->attributeAssignments = $attributeAssignments; if ($productInCart) { Yii::$app->cart->put($productInCart, $quantity); return ['status' => self::STATUS_SUCCESS, 'message' => Yii::t('app', 'Add Success.')]; } else { throw new HttpException(Yii::t('app', 'Please try again later.')); } }