Magento2 - How to lock customer cart?
-
23-02-2021 - |
题
- I have added product to customer cart programmatically with custom prices as quatation.
- Now customer should not add,remove or update cart items as it is fixed quatation.
How can i achieve this?
解决方案
- Add attribute to Quote if it is Quatation quote
$quote->setClientQuote(1)
;
Create plugin method before product operation on cart and block all
<type name="Magento\Checkout\Model\Cart">
<plugin name="interceptUpdateProductToCart" type="Ketan\Clientquote\Plugin\Clientquotecheck"/>
</type>
Create Plugin file
<?php
namespace Ketan\Clientquote\Plugin;
use \Magento\Framework\Message\ManagerInterface ;
class Clientquotecheck
{
/**
* @var ManagerInterface
*/
protected $_messageManager;
/**
* @var \Magento\Quote\Model\Quote
*/
protected $quote;
/**
* Plugin constructor.
*
* @param \Magento\Checkout\Model\Session $checkoutSession
*/
public function __construct(
\Magento\Checkout\Model\Session $checkoutSession,
ManagerInterface $messageManager
) {
$this->quote = $checkoutSession->getQuote();
$this->_messageManager = $messageManager;
}
/**
* @param \Magento\Checkout\Model\Cart $subject
* @param $data
* @return array
*/
public function beforeAddProduct(
\Magento\Checkout\Model\Cart $subject,
$productInfo,
$requestInfo = null
) {
$this->allowedMethod($subject);
return [$productInfo, $requestInfo];
}
/**
* Check if allowed function AddProductsByIds
*
* @param \Magento\Checkout\Model\Cart $subject
* @param array $productIds
* @return array
* @throws \Exception
*/
public function beforeAddProductsByIds(\Magento\Checkout\Model\Cart $subject, $productIds)
{
$this->allowedMethod($subject);
return [$productIds];
}
/**
* Check if allowed function UpdateItems
*
* @param \Magento\Checkout\Model\Cart $subject
* @param array $data
* @return array
* @throws \Exception
*/
public function beforeUpdateItems(\Magento\Checkout\Model\Cart $subject, $data)
{
$this->allowedMethod($subject);
return [$data];
}
/**
* Check if allowed function UpdateItem
*
* @param \Magento\Checkout\Model\Cart $subject
* @param int|array|\Magento\Framework\DataObject $requestInfo
* @param null|array|\Magento\Framework\DataObject $updatingParams
* @return array
* @throws \Exception
*/
public function beforeUpdateItem(
\Magento\Checkout\Model\Cart $subject,
$requestInfo = null,
$updatingParams = null
) {
$this->allowedMethod($subject);
return [$requestInfo, $updatingParams];
}
/**
* Check if allowed function
*
* @param \Magento\Checkout\Model\Cart $subject
* @param int $itemId
* @return int
* @throws \Exception
*/
public function beforeRemoveItem(\Magento\Checkout\Model\Cart $subject, $itemId)
{
$this->allowedMethod($subject);
return [$itemId];
}
/**
* Blocks method if active confirm mode is set true to session
*
* @throws \Exception
*/
public function allowedMethod($subject)
{
$quote = $subject->getQuote();
if ($quote->getClientQuote()) {
throw new \Exception('Action is blocked in quote confirmation mode.');
}
}
}