In your block file
use Magento\Catalog\Block\Product\ListProduct; <?phppublic 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;?>