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()
        ->setData('type', 'related')

       return $this->getResponse()->representJson(


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. Nov 3, 2018 at 16:40

1 Answer 1


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);

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 and acknowledge you have read our privacy policy.

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