Magento 2 — Module — Create Plugin
1 min readJul 16, 2019
Plugin is a feature that Magento 2 Has to execute something base on it’s function. It can be beforeMethodName, aroundMethodName, and/or afterMethodName. You can read on the official page of it here : https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html
How to Make it?
1. Create etc/di.xml
Go to etc
directory to make this file.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Controller\Adminhtml\Product\Save">
<plugin name="Icube_Training_AssignSaveProduct" type="Icube\Training\Plugin\AssignSaveProduct" sortOrder="1"/>
</type>
</config>
Explanation:
- Magento\Catalog\Controller\Adminhtml\Product\Save : Path to the Class that we want to intercept.
- Icube_Training_AssignSaveProduct : Plugin Name.
- Icube\Training\Plugin\AssignSaveProduct : Path to plugin/interceptor Class.
2. Create Plugin/ClassName.php
Inside the directory of Plugin
, make that Class with the name Plugin\AssignSaveProduct
:
<?phpnamespace Icube\Training\Plugin;use \Magento\Catalog\Controller\Adminhtml\Product\Save;class AssignSaveProduct
{
protected $categoryLinkManagement;public function afterExecute(Save $subject, $result) {
$data = $subject->getRequest()->getPostValue();
$training_id = 14;$categories = $data['product']['category_ids'];
if (array_search($training_id, $categories) === FALSE) {
array_push($categories, $training_id);
}$this->getCategoryLinkManagement()->assignProductToCategories(
$data['product']['sku'],
$categories
);return $result;
}private function getCategoryLinkManagement()
{
if (null === $this->categoryLinkManagement) {
$this->categoryLinkManagement = \Magento\Framework\App\ObjectManager::getInstance()
->get('Magento\Catalog\Api\CategoryLinkManagementInterface');
}
return $this->categoryLinkManagement;
}
}
Don’t forget to execute on command line bin/magento setup:di:compile
and bin/magento cache:flush
, then run it!