How to add one more add to cart button in magento 2 product view page and working of 2 buttons are independently [not conflict one button to another button] and validations also must to add product to cart. Please help me
Magento – magento 2 Adding one more Add to cart button
addtocartmagento2
Related Solutions
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;
$_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>
</button>
</form>
Create form in your template file and pass action for the same .Also you need to pass formkey .
Try below code :
<form data-role="tocart-form" action="<?php echo $block->getAddToCartUrl($_item); ?>" method="post">
<?php echo $block->getBlockHtml('formkey'); ?>
<button type="submit" title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>" class="action tocart primary" style="float:right;margin-left: 10px;">
<span><?php /* @escapeNotVerified */echo __('Add to Cart'); ?></span>
</button>
</form>
Best Answer
1.Addtocart/Newbutton/composer.json
2.Addtocart/Newbutton/registration.php
3.Addtocart/Newbutton/etc/module.xml
4.Addtocart/Newbutton/view/frontend/layout/catalog_product_view.xml
5.Addtocart/Newbutton/view/frontend/templates/product/view/addtocart.phtml