[英]Magento 2 - Observer event is not triggering while using REST product API add
下面的代碼用於使用 REST API 添加產品。 我想要實現的是通過webservice添加產品后,我需要調用一個觀察者來執行到另一個表的數據插入。
在通過管理員的網站中,如果我保存了產品,我可以調用觀察者,但在 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>
您在app/code/[NAMESPACE]/MODULE_NAME/etc/adminhtml/文件夾中創建了 events.xml 文件,因此只能從管理區域工作。
要使用 REST API 從前端工作,您可以將 events.xml 文件放在app/code/[NAMESPACE]/MODULE_NAME/etc/文件夾而不是app/code/[NAMESPACE]/MODULE_NAME/etc/adminhtml/文件夾中。
這是您可以聽到的事件列表,使用 rest api 添加產品
sales_quote_item_set_product
sales_quote_item_qty_set_after
sales_quote_product_add_after
sales_quote_item_save_before
sales_quote_item_save_after
這只是添加產品,而不是更新數量 sales_quote_add_item
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.