I have created before plugin for Add to cart functionality to check if product's custom attribute called My Tshirt(which is text field type) value "Jack" or "Jill".
Plugin work properly but in plugin code product is not loading the custom attributes. it;s loading product's default attributes. I tried to load the custom attribute using productRepository but unfortunately it's not working. I want return error message on the frontend if Attribute value is "Jill". in plugin code you can see "$product->getMyTshirt()" is not working also, if I try $product->getData('my_tshirt') that's also not working. How can I load the custom attribute value in there.
<type name="Magento\Checkout\Model\Cart">
<plugin name="interceptAddingProductToCart"
type="Jackson\Wyss\Model\Checkout\Cart\Plugin"
sortOrder="10"
disabled="false"/>
</type>
<?php
namespace Jackson\Wyss\Plugin\Model\Checkout\Cart;
use Magento\Framework\Exception\LocalizedException;
class Plugin
{
/**
* @var \Magento\Catalog\Model\ProductRepository
*/
protected $productRepository;
/**
* @param \Magento\Catalog\Model\ProductRepository $productRepository
*/
public function __construct(
\Magento\Catalog\Model\ProductRepository $productRepository
) {
$this->productRepository = $productRepository;
}
public function beforeAddProduct($subject, $productInfo, $requestInfo = null)
{
try {
$product = $this->productRepository->getById($productInfo->getId());
if($product->getMyTshirt() == 'Jill'){
throw new LocalizedException(__('Could not add Product to Cart'));
}
} catch (\Exception $e) {
throw new LocalizedException(__($e->getMessage()));
}
return [$productInfo, $requestInfo];
}
}
I tried to use observer controller_action_predispatch_checkout_cart_add as well. If I use that observer and add to cart on the frontend, it's simply reloading the page and in observer not getting product data as well. I followed below article but still no luck.
Any help would be appreciated!
Magento2 - How to stop a product from getting added to cart programmatically?