I used below event,
<event name="catalog_controller_product_view">
<observer name="custom_product_view_layout" instance="Vendor\Module\Observer\CheckProduct" />
</event>
Then in my observer file,
namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
class CheckProduct implements ObserverInterface
{
protected $_logger;
protected $_storeManager;
protected $messageManager;
protected $productRepository;
protected $_resultPageFactory;
public function __construct(
\Psr\Log\LoggerInterface $logger,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->_logger = $logger;
$this->_storeManager = $storeManager;
$this->messageManager = $messageManager;
$this->_resultPageFactory = $resultPageFactory;
$this->productRepository = $productRepository;
}
public function execute(Observer $observer) {
$product = $observer->getEvent()->getProduct();
if($this->_ciicustomerHelper->isCustomerLoggedIn()) {
try{
//Exam Service Api data
$productSku = $product->getSku();
$source_sku = $this->checkProduct($productSku);
if(isset($source_sku) && $source_sku != false) :
$message = "You can not buy this product";
$this->messageManager->addError(__($message));
endif;
} catch (\Exception $ex) {
$this->_logger->info("Message ".$ex->getMessage());
}
}
return $this;
}
public function checkProduct($productSku){
$connection = $this->getConnection();
$sql = "select * from custom_table where sku='".$productSku."'";
$resultProduct = $connection->query($sql);
$resultQuery = $resultProduct->fetchAll();
if(!empty($resultQuery)){
$parent_sku = $resultQuery[0]['parent_sku'];
return true;
}
}else{
return false;
}
}
}
This is not displaying any error message, can anyone help me on this please what is wrong in the code.
Thanks