0

I made a custom module for adding products to cart with help of ajax. Here I'm adding related products too. But the problem is that related products are not adding to cart. In my controller

public function execute()
{

    $productId = $this->getRequest()->get('id');
    $currentProduct = $this->_productFactory->create()->load($productId);
    $this->registry->register('product', $currentProduct);
    $resultRedirect = $this->_pageFactory->create();

    $message['html']= $resultRedirect->getLayout()
        ->createBlock("Magento\Catalog\Block\Product\ProductList\Related")
        ->setTemplate("Magento_Catalog::product/list/items.phtml")
        ->setData('type', 'related')
        ->toHtml();

       return $this->getResponse()->representJson(
            $this->jsonData->jsonEncode($message)
        );

}

I debugged in related-products.js and found that when I clicked on checkbox it is getting attached to function but not adding to cart.

enter image description here

  • Check in var/log/exception.log file What error is coming there. – Kirti Nariya Nov 3 '18 at 16:40
0

You need to add the product to the cart, something like the below. Please don't use the object manager and instead instantiate the Cart class via the constructor (it's below for demonstration purposes only).

/** @var $cart \Magento\Checkout\Model\Cart */
$cart = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Checkout\Model\Cart::class);
$requestInfo = new \Magento\Framework\DataObject(['qty' => 1]);
$cart->addProduct($currentProduct, $requestInfo);
$cart->save();

You'll probably also need to trigger an update of the mini cart, otherwise it'll probably only appear after a page refresh.

Also, I'd consider adding a fromkey check to ensure the request came from onsite.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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