I am working on custom Magento 2 site development. And I want to add the add to cart button on product view page.

Where there are 3 tabs i.e. Details, Reviews and Accessories/part.

I have created Accessories/Part content in phtml file in tabular format in which last column is "Add to Cart", and in that "Add to cart" button is placed

So, when user click on add to cart button it should add that product to cart

How should I do this functionality? Can anyone help me by which way I can do it.

  • HI, @ashwin if the answer is help full please make as accepted. Aug 9, 2017 at 12:13

1 Answer 1


In your block file

use Magento\Catalog\Block\Product\ListProduct;
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

    const PARAM_NAME_BASE64_URL = 'r64';
    const PARAM_NAME_URL_ENCODED = 'uenc';
    use Magento\Framework\App\Action\Action; 
   $_product=your 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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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