I want ADD TO CART button in [search entire store] search box, when we are searching for any product. I am getting only name and price when i am searching for a product, i want add to cart button with those . How can I do that, which files are responsible for that functionality. thanks in advance.
1 Answer
In to your custom block file you need to added this code.
<?php protected $listProductBlock; public function __construct(\Magento\Catalog\Block\Product\ListProduct $listProductBlock) { $this->listProductBlock = $listProductBlock; } public function getAddToCartPostParams($product) { return $this->listProductBlock->getAddToCartPostParams($product); } Now in your phtml file on top added this one :
use Magento\Framework\App\Action\Action; inside product collection you need to added code like this one :
<?php $postParams = $block->getAddToCartPostParams($_product); ?> <form data-role="tocart-form" data-product-sku="<?= $escaper->escapeHtml($_product->getSku()) ?>" action="<?= $escaper->escapeUrl($postParams['action']) ?>" method="post"> <input type="hidden" name="product" value="<?php echo $postParams['data']['product']; ?>"> <input type="hidden" name="<?php echo Action::PARAM_NAME_URL_ENCODED ?>" value="<?php echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>"> <?php echo $block->getBlockHtml('formkey') ?> <button type="submit" title="<?php echo $escaper->escapeHtmlAttr(__('Add to Cart')) ?>" class="action tocart primary" disabled> <span><?php echo $escaper->escapeHtml(__('Add to Cart')) ?></span> </button> </form> For More Information you can check default list file :
vendor/magento/module-catalog/view/frontend/templates/product/list.phtml