I want to remove products with call_to_order attribute is "yes". Add to cart button is disabled and phone number is showing.
If customer reorder from his account, and cart has this product, how to delete it from cart.
Please help.
You can delete the product from the cart programmatically in Magento 2 using the following code:
<?php
namespace Mage\Mohit\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
class RemoveFromCart implements ObserverInterface
{
/**
* @var \Magento\Checkout\Model\Cart
*/
protected $cart;
/**
* @var RequestInterface
*/
protected $request;
/**
* @param \Magento\Checkout\Model\Cart $cart
* @param RequestInterface $request
*/
public function __construct(
\Magento\Checkout\Model\Cart $cart,
RequestInterface $request
) {
$this->cart = $cart;
$this->request = $request;
}
/**
* Delete item from cart if call_to_order attribute is true
*
* @param \Magento\Framework\Event\Observer $observer
* @return $this
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$item = $observer->getEvent()->getData('quote_item');
$product = $item->getProduct();
if ($product->getCallToOrder()) {
$this->cart->removeItem($item->getItemId());
$this->cart->save();
}
return $this;
}
}
This code uses an observer to listen for the event that is triggered when a customer reorders from their account. When the event is triggered, the observer checks if the product's call_to_order attribute is set to true. If it is, the product is removed from the cart using the removeItem
method of the cart model and the changes are saved using the save
method.
You will need to create an observer in your module that listens to the event sales_model_service_quote_submit_before
and triggers the RemoveFromCart
observer class.
You can also use the following code in your module's events.xml
file:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_model_service_quote_submit_before">
<observer name="vendor_module_remove_from_cart" instance="Mage\Mohit\Observer\RemoveFromCart"/>
</event>
</config>
Let me know if any query.
THANKS.