how How to use Extension Attributes in Magento 2

I will explain how to use extension attributes in Magento 2 in this blog post. Magento 2 extension attributes allow you to extend the functionality of entities such as products, customers, and orders without modifying the core code. They provide a way to add custom data fields to these entities, enabling developers to tailor Magento to specific business requirements without the need for extensive customization or overrides.

Every interface that extends \Magento\Framework\Api\ExtensibleDataInterface can be extended with the help of the extension attributes. In extension attributes, the getExtensionAttributes method returns an auto-generated interface with attribute codes specified in extension_attributes.xml.

They often involve more complex data types than custom attributes, and these attributes do not appear in the Admin interface.

How to use Extension Attributes in Magento 2?

In this blog, I will create an extension attribute for the quote address to illustrate the use of the Extension Attribute. I will use that attribute value in the quote address.

Step 1: Create extension_attributes.xml file at app/code/Vendor/Module/etc/ and paste the below code to add extension attributes:

<?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="phonenumber" type="string" />
    </extension_attributes>
</config>

In the above code snippet, I have used a few attributes. Let’s see that meaning:

for: Add here the interface class name in which you want to add the extension attribute.
code:  The name of the attribute code
type: The data type of the attribute code. The data type can be string, int, array or complex type such as an interface. At the end of this tutorial, I have explained how to use interface or non-scaler data type in the extension attribute.

Here, I added phonenumber attribute for the extension attribute. It will be used for shipping addresses. For that, I will create one plugin and get the value of that attribute.

Step 2:  Create di.xml for initialize plugin at app/code/Vendor/Module/etc/ and paste the below code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Model\ShippingInformationManagement">
        <plugin name="phonenumber_extension_attribute"
                type="Vendor\Module\Plugin\Checkout\Model\ShippingInformationManagement"
                sortOrder="1" />
    </type>
</config>

Step 3: After that, Create ShippingInformationManagement.php file at app/code/Vendor/Module/Plugin/Checkout/Model/ and paste the below code to get and set phonenumber attribute value:

<?php
namespace Vendor\Module\Plugin\Checkout\Model;
 
use Magento\Quote\Model\QuoteRepository;
use Magento\Checkout\Model\ShippingInformationManagement;
use Magento\Checkout\Api\Data\ShippingInformationInterface;

class ShippingInformationManagement
{
    /**
     * Set extension Attribute Value
     * 
     * @param  ShippingInformationManagement $subject
     * @param                                $cartId
     * @param  ShippingInformationInterface  $addressInformation
     */
    public function beforeSaveAddressInformation(
        ShippingInformationManagement $subject,
        $cartId,
        ShippingInformationInterface $addressInformation
    ) {
        $shippingAddress = $addressInformation->getShippingAddress();
        $shippingAddressExtensionAttributes = $shippingAddress->getExtensionAttributes();
        if ($shippingAddressExtensionAttributes) {
            $phoneNumber = $shippingAddressExtensionAttributes->getPhonenumber();
            $shippingAddress->setPhonenumber($phoneNumber);
        }
    }
}

phonenumber field should be available in the quote_address table. You can create a new field in the database table using db_schema.xml file.
Now, you can check phonenumber value in shipping address. You will get this attribute value in that shipping address object.

Scaler and non-scaler attribute:

In the extension attribute, we can allow scalar values like boolean, int, float, and string values and also can allow objects that are non-scaler values and it is the beauty of the extension attribute.

Let’s understand how we can declare extension attributes of both data types:

For Scaler Attribue:

<?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="attribute_name" type="string"/>
    </extension_attributes>
</config>

In the above snippet, we declared the extension attribute type of the string which is a scaler data type. Replace attribute_name with any name.

For Non-scalar Attributes

<?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="attribute_name" type="Vendor\Module\Api\Data\ExtensionDataInterface[]" />
    </extension_attributes>
</config>

I’ve utilized the custom interface as a data type, which can include both get and set methods for accessing the property or value.

Conclusion:

To sum up, understanding the role of extension attributes in Magento 2 is essential for developers seeking to extend the platform’s functionality while adhering to best practices. With careful consideration and proper implementation, extension attributes empower businesses to adapt Magento to their unique needs without sacrificing stability or scalability.

Rate this post