Unable to get newly inserted Product's Id using After Plugin for Catalog Product save controller method
-
23-02-2021 - |
Question
I have created interceptor for catalog product controller's save action
<type name="Magento\Catalog\Controller\Adminhtml\Product\Save">
<plugin name="ricky_catalog_save_product"
type="Ricky\Catalog\Plugin\Product\Save" sortOrder="10"
/>
</type>
My plugin class is below
namespace Ricky\Catalog\Plugin\Product;
class Save {
public function afterExecute(
\Magento\Catalog\Controller\Adminhtml\Product\Save $subject,
$result)
{
$productId = $subject->productId; // This is not working
/**
echo $result->getProduct->getId(); die("prodid");
echo $subject->getProduct->getId(); die("prodid");
Both throw exception: Undefined property $getProduct
**/
/** $productId is provided in excute method in Save class
in Magento\Catalog\Controller\Adminhtml\Product\Save **/
}
}
For some reasons I have to use Plugin (Interceptor Design Pattern), I know I can get newly created prouduct id by using observer for catalog_product_save_after event. But please provide solution for plugins.
I am asking this after visiting This Solution
Thanks for help :)
Solution
The variable $product
is not accessible from outside the save
method. The only exceptioon is the event controller_action_catalog_product_save_entity_after
.
But the product builder puts the product into registry, so you may access the product from there.
This code should work in my opinion, but I didn't test it:
public function __construct(
\Magento\Framework\Registry $registry
)
{
$this->registry = $registry;
}
public function afterExecute(
\Magento\Catalog\Controller\Adminhtml\Product\Save $subject,
$result)
{
//get the product from registry
$product = $this->registry->registry('current_product');
$productId = $product->getId();
return $result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange