Magento 2 - 使用REST产品API添加时观察者事件不会激化
问题描述:
下面的代码用于使用REST API添加产品。我想要实现的是通过webservice添加产品后,我需要调用观察者来执行数据插入到另一个表。Magento 2 - 使用REST产品API添加时观察者事件不会激化
在通过管理员的网站上,如果我保存了产品,我可以调用观察者,但是在REST API中它不会触发。
// Post Data of Products
$sku = uniqid();
$productData = array(
'sku' => $sku,
'name' => 'Simple Product ' . uniqid(),
'visibility' => 4, /*'catalog',*/
'type_id' => 'simple',
'price' => 0.00,
'status' => 1,
'attribute_set_id' => 9,
'weight' => 1,
"extension_attributes"=> [
"stock_item"=> [
"manage_stock"=> 0,
"is_in_stock"=> 1,
"qty"=> "0"
]],
'custom_attributes' => array(
array('attribute_code' => 'category_ids', 'value' => ["3"]),
array('attribute_code' => 'description', 'value' => 'Simple Description'),
array('attribute_code' => 'short_description', 'value' => 'Simple Short Description'),
array('attribute_code' => 'chef_name', 'value' => 'Rafsan Chef'),
array('attribute_code' => 'servings', 'value' => '2 people'),
array('attribute_code' => 'cooking_time', 'value' => '20 minutes'),
array('attribute_code' => 'pdf_upload', 'value' => '123.pdf'),
array('attribute_code' => 'steps', 'value' => 'step 1 content###Step 2 content###Step3 Content'),
)
);
// creating Product using Magento 2 Rest API
$productData = json_encode(array('product' => $productData));
$ch = curl_init("http://127.0.0.1/magento/index.php/rest/V1/products");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS, $productData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
// the Product is Created using the Above Code
// i have created an observer in magento for product save after, that observer is working if it is saved from website admin End. but not working while saving through Rest Api.
// events.xml file created in app/code/[NAMESPACE]/MODULE_NAME/etc/adminhtml/events.xml
<event name="catalog_product_save_after">
<observer name="cus_recipe_saveafter" instance="Freshbox\Recipes\Observer\Productsaveafter" />
</event>
//感谢您的帮助
答
您创建events.xml文件中应用程序/代码/ [NAMESPACE]/MODULE_NAME的/ etc/adminhtml/文件夹,使得只有工作从管理区。
要同时从正面面积使用REST API的工作比你可以把events.xml文件中应用程序/代码/ [NAMESPACE]/MODULE_NAME的/ etc/文件夹而不是应用程序/代码/ [NAMESPACE]/MODULE_NAME/etc/adminhtml/文件夹。