I need to get the current product details in magento2 observer without using the registry.because magento latest version is deprecated this registry. I need the current product for reviews. when submit the form send the email
please help me.
This all depends on the event you are observering. Events can be fired from anywhere and usually have data assigned to the event itself - it may not always be the case that a product is defined in the registry when an event is fired.
If you are working with an event like catalog_product_save_after
for example, you can access the product being saved like:
public function execute(\Magento\Framework\Event\Observer $observer): void
{
$product = $observer->getEvent()->getData('product');
if (!$product instanceof \Magento\Catalog\Api\Data\ProductInterface) {
return;
}
// We now have a valid $product, do whatever with it.
$product->setData('foo', 'bar');
}
EDIT:
As you've mentioned in comments, it appears the event in question is review_save_after
. The below code should work in your observer class:
/* @var $review \Magento\Review\Model\Review */
$review = $observer->getEvent()->getObject();
foreach ($review->getProductCollection() as $product) {
// We now have access to each $product associated to the review.
$product->setData('foo', 'bar');
};
events.xml
file.
Commented
Feb 13, 2023 at 8:58
Yes, but the deprecated here is just a notice, and It stands in code for a long time, I'm using it day-by-day tasks and have no consequences, the registry still contains the data, so why not,
If you don't want to use Registry, you can try using $this->request->getParams().
You can get id in params,
$this->getRequest()->getParams();
For Product Id,
$this->request->getParam('product_id'); // Use this class in construct() \Magento\Framework\App\RequestInterface
In your Controller file
protected $request;
public function __construct(
\Magento\Framework\App\RequestInterface $request
) {
$this->request = $request;
}
public function execute()
{
$this->request->getParam('product_id');
}
To get id in getParam() you need to pass it as hidden field in phtml file
In your phtml file,
<input type="hidden" name="product_id" value="<?php echo $product_id ?>">
In Observer & Plugin File:- It depends on which event you want to observe and same goes for the plugin. If you're passing as hidden field and calling a observer on that particular event, you can get id as i mentioned above.