How to use extension_attributes in Magento2
-
29-09-2020 - |
Question
Is there anyone that can give me an example on how to use extension_attributes
in Magento2?
Solution
Suppose we create an order delivery date, when the customer select shipping then the customer can select a delivery date. So you can create a extension attribute for \Magento\Checkout\Api\Data\ShippingInformationInterface in following way
<?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\Checkout\Api\Data\ShippingInformationInterface">
<attribute code="delivery_date" type="string"/>
</extension_attributes>
</config>
So now you can access this value when you using \Magento\Checkout\Api\Data\ShippingInformationInterface as di.
So in that case Magento\Checkout\Model\ShippingInformationManagement this class use \Magento\Checkout\Api\Data\ShippingInformationInterface as a params for saveAddressInformation method. So you can access following way:
$extAttributes = $addressInformation->getExtensionAttributes();
$deliveryDate = $extAttributes->getDeliveryDate();
For more details(Magento 2 Official Documentation)
Here is an example:
Pick Extension Attributes value
[Update]
You can set extension_attributes by setExtensionAttributes method. Following class is an example: Click Here