Reading list Switch to dark mode

    How to add extension attribute in Magento 2

    Updated 26 February 2024

    Extension Attribute in Magento 2

    Here we learn, how to add extension attribute in magento 2. Extension attributes used to extend interface functionality. They often use more complex data types than custom attributes and these attributes do not appear in the Admin.
    An extension attribute allows us to overcome the limitations of scalar values. With an extension attribute, we can extend both EAV and non-EAV with complex objects.

    1. Create app/code/Webkul/DemoModule/etc/extension_attributes.xml

    A) For Scalar Attibutes
    Attributes that can only contain scalar values, that is, booleanintfloat, or string values.

    <?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>

    B) For Non-scalar Attributes
    Attributes that can use objects to have more complex types. You will require to create a custom interface for these 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="wk_custom_data" type="Webkul\DemoModule\Api\Data\CustomDataInterface[]" />
        </extension_attributes>
    </config>

    2. Now you can set/get these attributes value by creating the instance of Magento/Checkout/Api/Data/ShippingInformationInterface.php interface.

    Start your headless eCommerce
    now.
    Find out More
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $addressInformation = $objectManager->create('Magento\Checkout\Api\Data\ShippingInformationInterface');
    $extAttributes = $addressInformation->getExtensionAttributes();
    
    $selectedShipping = $extAttributes->getCustomShippingCharge(); //get custom attribute data.

    However, in case of any query or questions regarding the Magento 2 Extensions, you can create a ticket at webkul.uvdesk.com or contact us at store.webkul.com/contacts/ to let us know your views to make the plugin better.

    Hope this will help you.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    4 comments

  • Sreedevi
    • Mahesh Singh (Moderator)
  • Raviteja
    • Praful Rajput
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home