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, boolean
, int
, float
, 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.
$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.
4 comments
And you can set the extension attributes data like this: Example Image , then you can access it, as i explained in Blog Step 3.
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.