This article will throw some light on how one can use the extension attributes in Magento 2. Extension attributes are primarily containers that are used for adding an additional piece of information to our entities.
Every interface that extends
\Magento\Framework\Api\ExtensibleDataInterface can be extended with the help of the extension attributes. The methods defined in
ExtensibleDataInterface grants access to the objects that contain the additional data.
Below example will give you a clear picture of what we are trying to explain. For this first, we will create one module named DemoModule.
Step 1 – Declare Extension Attributes
We will be declaring the extension attributes in
<?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="custom_shipping_charge" type="string"/> </extension_attributes> </config>
This means that we are extending our shipping information Interface with an attribute. It’s accessible from
Below are short descriptions that will explain what the words stand for:
- for – The fully-qualified type name with the namespace that processes the extensions. The value must be a type that implements `ExtensibleDataInterface`. The interface can be in a different module.
- code – The name of the attribute. The attribute name should be in snake case (the first letter in each word should be in lowercase, with each word separated by an underscore).
- type – The data type. This can be a simple data type, such as string or integer, or complex type, such as an interface.
Step 2 – Clear Generated Files
Now clear the
var/generation when you run
setup:di:compile command, new getter and setter methods will be added in
Step 3 – Set/Get Attributes
Now you can set/get these attributes value by creating the instance of
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $addressInformation = $objectManager->create('Magento\Checkout\Api\Data\ShippingInformationInterface'); $extAttributes = $addressInformation->getExtensionAttributes(); $selectedShipping = $extAttributes->getCustomShippingCharge();
One important thing to note, for the Extension Attributes to work as proposed we always need to query the entity for the existing extension_attributes via
getExtensionAttributes() before using the extension attribute factory to create a new one. In case if we omit this check any previously set extension attributes on the entity will we wiped off.
One of the benefits that you will get from using Extension Attributes is that your added attribute data is automatically available through an API request.