In Magento 2, extension attributes extend the default functionality and generally use more complex data types than the custom attributes.
Us developers cannot change the API data interfaces defined in the default Magento. But these entities have the extension attributes feature.
They are the additional data that we want to add in our entity. And the post gives the solution to add extension attribute to entity in Magento 2.
The extensibility of default features is what makes Magento 2 stand apart from other CMSs. However, there is the cost of this flexibility, i.e., stability. The extensibility and stability are two opposite end of the poles and to create a right balance, Service Contracts are introduced.
Extension Attributes are used to allow for customization of the strict Service Contracts. These attributes do not appear on the GUI.
Method To Add Extension Attribute to Entity In Magento 2:
Create app/code/Vendor/Extension/etc/extension_attributes.xml
<?xml version="1.0"?> <config> <extension_attributes for="Path\To\Interface"> <attribute code="name_of_attribute" type="datatype"> </attribute> </extension_attributes> </config>
Example: Create app/code/Vendor/Extension/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\Quote\Api\Data\AddressInterface"> <attribute code="attribute_name" type="string"/> </extension_attributes> </config>
That’s it.
Feel free to share the solution on social media for helping the fellow developers.
Thank you.