В настоящее время мы разрабатываем веб-магазин на базе ERP с Sylius. Одна из особенностей заключается в том, что клиент может выбирать несколько размеров и количества и добавлять их в корзину в одном действии.Sylius Добавить в корзину через CartItemController дает 0,00 всего
Обычно Sylius будет работать с запросом ItemResolver
только для одного варианта. Мы попытались переопределить CartItemController
, чтобы мы могли зацикливать переменные запроса и добавить все предметы в корзину.
Мы пытались использовать этот код:
try {
// When we have multiple
$reqSize = $request->request->get('size');
$reqQuantity = $request->request->get('quantity');
$reqProductID = $request->request->get('product_id');
$reqColorID = $request->request->get('variant_color_id');
if (null !== $reqSize && null !== $reqQuantity && null !== $reqProductID && null !== $reqColorID && count($reqSize) === count($reqQuantity)) {
$provider = $this->get('sylius.cart_provider'); // Implements the CartProviderInterface.
$currentCart = $provider->getCart();
$priceCalculator = $this->get('sylius.price_calculator');
$availabilityChecker = $this->get('sylius.availability_checker');
$productRepo = $this->get('sylius.repository.product');
$variantRepo = $this->get('sylius.repository.product_variant');
$sizeRepo = $this->get('jartazi.repository.sizegrid_size');
$colorRepo = $this->get('jartazi.repository.color');
$product = $productRepo->find(intval($reqProductID));
$color = $colorRepo->find(intval($reqColorID));
for ($i = 0; $i < count($reqSize); $i++) {
$size = $sizeRepo->find(intval($reqSize[$i]));
$variant = $variantRepo->findOneBy(['object' => $product, 'size' => $size, 'color' => $color]);
$quantity = intval($reqQuantity[$i]);
if (null === $variant) {
throw new ItemResolvingException('Selected item is out of stock.');
}
if (null !== $product && null !== $color && null !== $size && null !== $variant) {
// Make a cart item
$item = $this->get('sylius.factory.cart_item')->createNew();
$item->setSize($size);
$item->setVariant($variant);
$item->setQuantity($quantity);
$context = ['quantity' => $quantity];
if (null !== $customer = $cart->getCustomer()) {
$context['groups'] = $customer->getGroups()->toArray();
}
$item->setUnitPrice($priceCalculator->calculate($variant, $context));
// Check for equal products
foreach ($currentCart->getItems() as $cartItem) {
if ($cartItem->equals($item)) {
$quantity += $cartItem->getQuantity();
break;
}
}
if (!$availabilityChecker->isStockSufficient($variant, $quantity)) {
throw new ItemResolvingException('Selected item is out of stock.');
}
$event = new CartItemEvent($cart, $item);
// Update models
$eventDispatcher->dispatch(SyliusCartEvents::ITEM_ADD_INITIALIZE, $event);
$eventDispatcher->dispatch(SyliusCartEvents::CART_CHANGE, new GenericEvent($cart));
$eventDispatcher->dispatch(SyliusCartEvents::CART_SAVE_INITIALIZE, $event);
// Write flash message
$eventDispatcher->dispatch(SyliusCartEvents::ITEM_ADD_COMPLETED, new FlashEvent());
}
}
return $this->redirectAfterAdd($configuration);
}
} catch (ItemResolvingException $exception) {
// Write flash message
$eventDispatcher->dispatch(SyliusCartEvents::ITEM_ADD_ERROR, new FlashEvent($exception->getMessage()));
return $this->redirectAfterAdd($configuration);
}
Но если мы добавим один к тележке, тележка общая остается 0,00
ли мы что-то отсутствует, чтобы иметь правильные суммы при добавлении CartItem без ItemResolver?
Заранее спасибо.
'OrderItem' создается и добавляется в' Cart', а unit_total и total остается '0'. Другие вещи устанавливаются как unit_price и количество. – spyral