4

How can I add "add to cart button" in my custom phtml file in Magento 2 ?
Please describe how default Magento 2 add to cart button working.

7

you can add button in custom phtml file as follow, I have done this in custom module

In your block file

use Magento\Catalog\Block\Product\ListProduct;
<?php
public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
         \Magento\Catalog\Block\Product\ListProduct $listProductBlock,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->listProductBlock = $listProductBlock;
    }

public function getProductCollection()
{
    /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
   $collection = $this->_productCollectionFactory->create()->addAttributeToSelect('*')->load();
    return $collection;
}
public function getAddToCartPostParams($product)
{
    return $this->listProductBlock->getAddToCartPostParams($product);
}
?>

get productlist in view file

<?php 
const PARAM_NAME_BASE64_URL = 'r64';
const PARAM_NAME_URL_ENCODED = 'uenc';
use Magento\Framework\App\Action\Action; 
$_productCollection = $block->getProductCollection();
?>
<?php foreach ($_productCollection as $_product): ?>
    <?php $postParams = $block->getAddToCartPostParams($_product); ?>
    <?php echo $_product->getName()?>
    <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 Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>">
        <?php echo $block->getBlockHtml('formkey')?>
        <?php $storeManager = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Store\Model\StoreManagerInterface'); ?>
            <button type="submit"
                    title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
                    class="action tocart primary">
                <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
            </button>
    </form>
<?php endforeach;?>
4

You can use

<?php $postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
$postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()])
?>
<button class="action tocart primary"
        data-post='<?php /* @escapeNotVerified */ echo $postData; ?>'
        type="button" title="<?php /* @escapeNotVerified */ echo __('Add to Cart1') ?>">
    <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
</button>

Where $_item is your product.

Hope it helps.

  • Hi, I appreciate this was nearly 2 years ago but this has worked perfectly for me, is there any way to adjust the quantity? – green_arrow Feb 8 '18 at 13:10
  • not working. Click on Add To Cart button nothing happen – HaFiz Umer Oct 21 at 8:22
3

You can use this in your phtml file for add to cart button

  <?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">

       <span>Add to Cart</span>
     </button>
 </form>
  • This is works well for simple products but when is configurable with variation it add to cart but it has no details in the mini-cart do you know a fix for this. thanks – Juliano Vargas Sep 19 '18 at 12:06
  • How does $product get defined? – Jason Diehl Nov 9 '18 at 21:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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