i am using magento 2.1.5, and i have two tax classes. and i want to add only one tax class product in cart at a time. if customer try to add another tax class product, it will throw the massage.
for this i tried by adding plugin.
public function beforeaddItem(\Magento\Quote\Model\Quote $subject,$item)
{
$productTax = array();
$storeId = $this->storeManager->getStore()->getId();
$items = $this->quote->getItems();
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/cartblock.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info(json_encode($items));
foreach($items as $_item) {
$writer = new \Zend\Log\Writer\Stream(BP . 'var/log/cartblock.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info(json_encode($_item->getData()));
$productList = $this->productRepository->getById($_item->getProductId(), false, $storeId, true);
$productTax[] = trim($productList->getTaxClassificationKey());
}
$productNew = $this->productRepository->getById($item->getProductId(), false, $storeId, true);
if(!empty($productTax) && !in_array(trim($productNew->getTaxClassificationKey()),$productTax)){
throw new \Magento\Framework\Exception\LocalizedException(__('You only order Same Tax Class product.'));
}
return [$item];
}
}
But Its not working. Please help.