Menu Close
    Searching for an experienced eCommerce & Marketplace Development Company ?

    How to add extension attribute in Magento2

    Extension Attribute in Magento2

    Here we learn, how to add extension attribute in magento2. Extension attributes used to extend interface functionality.

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

    <?xml version="1.0"?>
    <!-- 
    	/**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Webkul_DemoModule
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
     -->
    <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>

    2. Now clear the var/generation when you run setup:di:compile command, new getter and setter methods will be added in /var/generation/Magento/Checkout/Api/Data/ShippingInformationExtensionInterface.php

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

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $addressInformation = $objectManager->create('Magento\Checkout\Api\Data\ShippingInformationInterface');
    $extAttributes = $addressInformation->getExtensionAttributes();
    
    $selectedShipping = $extAttributes->getCustomShippingCharge(); //get custom attribute data.
    
    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    4 comments

  • Sreedevi
    This is really good blog. I have one question on this. Shall i use this same extension attributes for admin order.
  • Raviteja
    Hii,
    in your 3rd step you are creating the instance of Magento/Checkout/Api/Data/ShippingInformationInterface.php interface, where exactly are you creating.are you changing any vendor file or are you using custom module, i got stuck in this.
    • Praful Rajput
      @raviteja, you have to define it into your custom module.
  • Back to Top