Add to Cart Button in CMS Page – Magento 2 Guide

addtocartcms-pagesmagento-2.1

In Magento2.1, I'm able to load a product in CMS page using:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->load(1);

Then I'm trying (without any luck) to display the add-to-cart link using:

<?php echo Mage::helper('checkout/cart')->getAddUrl($product) ?>

What am I doing wrong?

p.s. I saw many Q&A about this topic but none of them seems to work in my project.

EDIT

I've just found the following that actually displays the link, but it completely breaks the layout.

$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');
$addToCartUrl =  $listBlock->getAddToCartUrl($product);

echo $addToCartUrl;

EDIT 2

so I did some tests and got inconsistent results.

I was able to display an add-to-cart button with the following:

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');
    $addToCartUrl =  $listBlock->getAddToCartUrl($product);
?>

<form data-role="tocart-form" action="<?php echo $addToCartUrl; ?>" method="post">
    <?php echo $block->getBlockHtml('formkey')?>
        <button type="submit"
            title="Add to Cart"
            class="action tocart primary dark">
            <h2>Add to Cart</h2>
        </button>
 </form>

This button does not add anything to the cart untill I click on the link built with:

<a href="<?php echo $objectManager->get('Magento\Checkout\Helper\Cart')->getAddUrl($product) ?>">ADD TO CART</a>

After that, the JS button start working correctly.. I'm currently at a dead end

Best Answer

You are using Mage class, which has been removed in Magento 2. The Magento 2 equivalent of

<?php echo Mage::helper('checkout/cart')->getAddUrl($product) ?>

is as below:

Method 1

<?php echo $objectManager->get('Magento\Checkout\Helper\Cart')->getAddUrl($product) ?>

Method 2:

Also, Note that you should avoid using Object Manager in Magento 2. It is not a good practice. So, to avoid using Object Manager you have to write following in your template's Block File:

protected $_cartHelper;

public function __construct(
   \Magento\Checkout\Helper\Cart $cartHelper
) {
   $this->_cartHelper = $cartHelper;
}

public function getAddToCartUrl($product, $additional = []) {
   return $this->_cartHelper->getAddUrl($product, $additional);
}

For method 2, you can use Magento\Catalog\Block\Product\View class's getAddToCartUrl function as your reference.

Related Topic