Add to Cart in custom block Homepage Magento 2
Domanda
I am trying to add a Add to cart button in a custom block being added to the homepage.
I've looked at many SO / MSE posts and all refer to Object Manager but I know it's not meant to be used, and from the look of what's been said I can see it being removed a few versions down the line, or at least changed in a way where all the code being suggested will break.
The closest thing I've found to get a working button is:
<?php $collection = $this->getCollection(); ?>
<?php $postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper'); ?>
<?php $postData = $postDataHelper->getPostData($block->getAddToCartUrl($prod), ['product' => $prod->getEntityId()]) ?>
but it returns a JS error in console:
TypeError: params.data is undefined
params.data.form_key = formKey;
This makes me think, It expects few things to be in a form? So I guess my real question is, what is the Magento 2 equivalent of
<?php echo $this->getAddToCartUrl($_product); ?>
Soluzione
Using Widget
We can add the listing product on Homepage by using Widget. CONTENT > Pages > Choose home page cms > Content > Insert Widget. We can choose Widget Type: Catalog Products List
If we want the Widget product to use Ajax, we need to create a form submit for each product. Remember to add form key for it.
app/design/frontend/VendorTheme/default/Magento_CatalogWidget/templates/product/widget/content/grid.phtml
.....
<?php
$postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
$postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()]);
$postParams = json_decode($postData, true);
?>
<form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post">
<input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
<input type="hidden" name="<?php /* @escapeNotVerified */ echo Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED]; ?>">
<?php echo $block->getBlockHtml('formkey')?>
<button type="submit" title="<?php /* @escapeNotVerified */ echo __('Add to Cart') ?>" class="action tocart primary">
<span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
</button>
</form>
......
Adding Javascript:
<?php if (!$block->isRedirectToCartEnabled()) : ?>
<script type="text/x-magento-init">
{
"[data-role=tocart-form]": {
"catalogAddToCart": {}
}
}
</script>
<?php endif; ?>
See more here: vendor/magento/module-catalog/view/frontend/templates/product/list.phtml
If we want to create a custom listing product block with Ajax add to cart, we can follow the same logic.