Is there anyone that can give me an example on how to use extension_attributes
in Magento2?
-
Have you looked at this?– Steve JohnsonMay 1, 2016 at 15:29
-
1Yes, I did, but it was not so clear to me– Phoenix128_RiccardoTMay 1, 2016 at 16:13
-
magento.stackexchange.com/questions/87452/…– nevvermindMay 1, 2016 at 20:13
1 Answer
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
-
-
-
Great, but one thing is missing here: Where exactly are extension attributes stored? Do I have to provide code for saving and retrieving attributes myself or can Magento handle that (like with custom attributes)? Jun 1, 2016 at 14:59
-
1Thanks @SohelRana, It's working fine in default Magento setup, but when I install OneStepCheckout module then i can't get value in the post, I mean in quote object so what should i need to change for that.... I get this type value in quote object [delivery_date] => 0000-00-00 00:00:00 ?– DhruminNov 17, 2017 at 9:45
-
1@MartinWickman yes it is the responsibility of the developer to implement logic for retrieving and persisting of extension attribute data. The concept is, you have some possibly complex data introduced by your Module for Product Entities and this data might come from one or more database tables, or some other data source, it should not matter. Using the Plugin system, target the ProductRepository's methods for loading (e.g., afterGet, afterGetList). Here, you retrieve your data (from wherever) and add it to the Entity's ExtensionAttributes. This seems arduous but is very flexible and powerful. Feb 11, 2019 at 20:07