0

I'm trying to add products to cart programmatically using \Magento\Quote\Api\CartRepositoryInterface since \Magento\Checkout\Model\Cart is already deprecated. My code is successfully being inserted in quote, quote_item table and other tables. but it's not creating any entries in quote_id_mask table. I don't know what's lacking in my code.

Not also sure if it's the problem that's causing the product to not appear in the front end.

public function __construct(
    Context $context,
    \Magento\Checkout\Model\CartFactory $cartFactory,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\Quote\Model\QuoteFactory $quoteFactory,
    \Magento\Quote\Model\Quote\ItemFactory $quoteItemFactory,
    \Magento\Quote\Api\Data\CartInterfaceFactory $cartInterface,
    \Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
    \Magento\Quote\Api\Data\CartItemInterfaceFactory $cartItemInterface,
    \Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
    \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress
){
    parent::__construct($context);
    $this->cartFactory = $cartFactory;
    $this->productRepository = $productRepository;
    $this->quoteFactory = $quoteFactory;
    $this->quoteItemFactory = $quoteItemFactory;
    $this->cartInterface = $cartInterface;
    $this->cartRepositoryInterface = $cartRepositoryInterface;
    $this->cartItemInterface = $cartItemInterface;
    $this->storeManagerInterface = $storeManagerInterface;
    $this->remoteAddress = $remoteAddress;
}

public function execute()
{
    $request_data = [
        ['sku' => 'product-sku', 'type' => 'sample']
    ];

    $cart = $this->cartInterface->create();
    $cart->setStoreId($this->storeManagerInterface->getStore()->getId());
    $cart->setRemoteIp($this->remoteAddress->getRemoteAddress());

    foreach($request_data as $request){
        $product = $this->productRepository->get($request['sku']);

        $item = $this->cartItemInterface->create();
        $item->setProduct($product);
        $item->setQty(1);

        $cart->addItem($item);

        $this->cartRepositoryInterface->save($cart);
    }

    die('test');
}

2 Answers 2

0

I couldn't actually test this but this example might help you

0

Replace your code to below.

foreach($request_data as $request){
        $product = $this->productRepository->get($request['sku']);

        $item = $this->cartItemInterface->create();
        $item->setProduct($product);
        $item->setQty(1);

        $cart->addItem($item);
    }
$this->cartRepositoryInterface->save($cart);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.