17

Is there anyone that can give me an example on how to use extension_attributes in Magento2?

21

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:

extension_attributes

Pick Extension Attributes value

[Update]

You can set extension_attributes by setExtensionAttributes method. Following class is an example: Click Here

| improve this answer | |
  • So what is setExtensionAttributes for? – Phoenix128_RiccardoT May 1 '16 at 16:13
  • I updated with real example – Sohel Rana May 1 '16 at 18:20
  • 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)? – Martin Wickman Jun 1 '16 at 14:59
  • 1
    Thanks @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 ? – Dhrumin Nov 17 '17 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. – John Hall Feb 11 '19 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.