Magento 2如何通过Rest API获取自定义属性的值

如何通过Rest API获取自定义属性的值也是有用的教程,以便开发人员可以在运行自己的Magento 2商店时添加更多自定义字段。本主题将介绍在获取自定义属性的值时使用Rest API所必须遵循的所有基本步骤。

通过Rest API获取自定义属性值的概述

步骤1:添加新列并为现有订单设置值

要获得自定义属性,第一件事是插入一个新列(mageplaza_helloworld_custom_attribute在表sales_order中称为)并为现有订单设置值。

步骤2:添加特定的新文件

由于Magento 2在Rest API的响应中不支持新字段,因此必须\app\code\Mageplaza\HelloWorld\etc\extension_attributes.xml在扩展文件夹中添加一个包含以下内容的文件:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
  <extension_attributes for="Magento\Sales\Api\Data\OrderInterface">
      <attribute code="mageplaza_helloworld_custom_attribute" type="string" />
  </extension_attributes>
</config>

步骤3:添加观察值

要将自定义属性注入到中extension_attributes.xml,必须为事件``sales_order_load_after via \ app \ code \ Mageplaza \ HelloWorld \ etc \ events.xml`文件添加观察值。

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
  <event name="sales_order_load_after">
      <observer name="sales_order_load_helloworld_custom_attribute" instance="Mageplaza\HelloWorld\Observer\Sales\OrderLoadAfter" />
  </event>
</config>

步骤4:添加文件以处理事件

生成一个文件app\code\Mageplaza\HelloWorld\Observer\Sales\OrderLoadAfter.php来管理sales_order_load_after上一步中的事件。

<?php
namespace Mageplaza\HelloWorld\Observer\Sales;

use Magento\Framework\Event\ObserverInterface;

class OrderLoadAfter implements ObserverInterface
 
{
 
public function execute(\Magento\Framework\Event\Observer $observer)
 
{
 
    $order = $observer->getOrder();
 
    $extensionAttributes = $order->getExtensionAttributes();
 
 
 
    if ($extensionAttributes === null) {
 
        $extensionAttributes = $this->getOrderExtensionDependency();
 
    }
 
    $attr = $order->getData('helloworld_custom_attribute');
 
    $extensionAttributes->setHelloWorldCustomAttribute($attr);
 
    $order->setExtensionAttributes($extensionAttributes);
 
}
 
   
 
private function getOrderExtensionDependency()
 
{
 
    $orderExtension = \Magento\Framework\App\ObjectManager::getInstance()->get(
        '\Magento\Sales\Api\Data\OrderExtension'
    );
 
    return $orderExtension;
 
}
 
}

步骤5:清理文件夹以激活功能

var\generation如果要激活功能setHelloWorldCustomAttribute()getHelloWorldCustomAttributevar\generation\Magento\Sales\Api\Data\OrderExtension.php自动生成的文件中,则需要删除该文件夹。

/**
  * @return string|null
  */
public function getHelloWorldCustomAttribute()
{
     return $this->_get('helloworld_custom_attribute');
}

/**
  * @param string $helloWorldCustomAttribute
  * @return $this
  */
public function setHelloWorldAttribute($helloWorldCustomAttribute)
{
	 $this->setData ('helloworld_custom_attribute', $helloWorldCustomAttribute);
	 return $this;
}
赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论