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