Get Add to Cart URL in Custom Template File – Magento 2

addtocartmagento2

i am not able to get add to cart url in my custom template files , here is my code

$postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
$postData = $postDataHelper->getPostData($block->getAddToCartUrl($product), ['product' => $product->getEntityId()]);

O/p:->

string(110) "{"action":null,"data":{"product":"392","uenc":"aHR0cDovLzQ1LjMzLjEyMi42Ni9ib25hZ2UvaW5kZXgucGhwL3Rlc3QtMi8,"}}"

My add to cart form code is :

<form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post" enctype="multipart/form-data" validate="validate">
        <input type="hidden" name="product" value="<?php echo $postParams['data']['product']; ?>">
        <input type="hidden" name="<?php echo \Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php echo $postParams['data'][\Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED]; ?>">
        <?php echo $block->getBlockHtml('formkey') ?>
       <div class="view-detail">
      <button type="submit" title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>" class="action tocart primary">
      <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
     </button> </div>
    </form>

while i submit form only page is load because i am getting null in post action.
Please help me to complete my add to cart code in my custom template files

Best Answer

You can try this, it work for me.

<?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')?>
    <div class="btn">
        <button type="submit" title="Add to Cart" class="action tocart primary">
            <span>Add to Cart</span>
        </button>
    </div>   
 </form>
Related Topic