Extension attributes in adobe commerce magento 2 . Extension attributes function as containers for additional data, extending functionality, and often incorporating more complex data than custom attributes.

We are going to explore and cover the significance of Magento 2 extension attributes in Adobe Commerce. Delve into optimizing product attributes for peak performance and gain expert tips for maximizing your Adobe Commerce experience for Magento 2 extension attributes in Adobe Commerce.

Magento 2 Extension Attributes function as containers for additional data, extending functionality, and often incorporating more complex data than custom attributes.

Every attribute that extends the class Magento\Framework\Api\ExtensibleDataInterface to implement extension attribute. In your code you have to define getExtensionAttributes() and setExtensionAttributes(*ExtensionInterface param)

Declare Magento 2 Extension Attributes:


You need to create /etc/extension_attributes.xml file to define module’s extension attribute.

<config>
    <extension_attributes for="Path\To\Interface">
        <attribute code="name_of_attribute" type="datatype">
           <resources>
              <resource ref="permission"/>
           </resources>
           <join reference_table="" reference_field="" join_on_field="">
              <field>fieldname</field>
           </join>
        </attribute>
    </extension_attributes>
</config>

Let us understand each fields meaning.

1. 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. Ex: Magento\Quote\Api\Data\TotalsInterface

2. 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). Ex: gift_cards_amount_used

3. type: The data type. This can be a simple data type, such as string or integer, or complex type, such as an interface. Ex: float , Magento\CatalogInventory\Api\Data\StockItemInterface

4. ref: Optional. Restricts access to the extension attribute to users with the specified permission. Ex: 
Magento_CatalogInventory::cataloginventory

5. reference_table: The table involved in a join operation. See Searching extension attributes for details. Ex:  admin_user

6. reference_field: Column in the reference_table Ex: user_id

7. join_on_field: The column of the table associated with the interface specified in the for keyword that will be used in the join operation. Ex: store_id

8. field: One or more fields present in the interface specified in the type keyword.
You can specify the column="" keyword to define the column in the reference_table to use. The field value specifies the property on the interface which should be set. 
Ex: <field>firstname</field>
<field>lastname</field>
<field>email</field>
<field column="customer_group_code">code</field>

Searching Extension Attributes:


System uses join directive to add external attribute to a collection and make the collection filterable. The join element in the extension_attribute.xml file defines which object field and database table/column to use as source of search.

In this example, we are adding an attribute of the type stock_item from Magento\CatalogInventory\Api\Data\StockItemInterface to Magento\Catalog\Api\Data\ProductInterface.

<extension_attributes for="Magento\Catalog\Api\Data\ProductInterface">
    <attribute code="stock_item" type="Magento\CatalogInventory\Api\Data\StockItemInterface">
        <join reference_table="cataloginventory_stock_item" reference_field="product_id" join_on_field="entity_id">
            <field>qty</field>
        </join>
    </attribute>
</extension_attributes>

When getList called it returns a list of ProductInterfaces by populating the stock_item with a join operation in which StockItemInterface qty field comes from cataloginventory_stock_item the table where the products entity_id joined with cataloginventory_stock_item.product_id column.

When you add search extension attribute you must consider that this can cause ambiguity in selection of field in resulting the sql query when using REST APIs. In this case the rest API call must explicitly specify both table name and field to use selection.

For example, the following configuration may introduce ambiguity when getting orders via REST API. The configuration constructs a query like SELECT …. FROM sales_order AS main_table LEFT JOIN sales_order. This creates an ambiguity for all columns from the sales_order table in that MySQL cannot determine if it should take them from the main_table or from the sales_order from the JOIN clause.

<config>
    <extension_attributes for="Magento\Sales\Api\Data\OrderInterface">
        <attribute code="field1" type="int">
            <join reference_table="sales_order" join_on_field="entity_id" reference_field="entity_id">
                <field>field1</field>
            </join>
        </attribute>
    </extension_attributes>
</config>

REST API Endpoint:

GET http://<host>/rest/default/V1/orders

Payload:

searchCriteria[filter_groups][0][filters][0]
[field]=main_table.created_at&searchCriteria
[filter_groups][0][filters][0][value]=2021-09-14%2000:00:00
&searchCriteria[filter_groups][0][filters][0]
[conditionType]=from
&searchCriteria[filter_groups][1][filters][0]
[field]=main_table.created_at
&searchCriteria[filter_groups][1][filters][0]
[value]=2021-09-14%2023:59:59
&searchCriteria[filter_groups][1][filters][0]
[conditionType]=to
&searchCriteria[pageSize]=10
&searchCriteria[currentPage]=86

Magento 2 Extension Attributes authentication:


Existing permissions can restrict any field defined as an extension attribute.. The following code examples define stock_item as an extension attribute of the CatalogInventory module. We treat CatalogInventory as a third-party extension, and we restrict access to inventory data due to the sensitivity of in-stock item quantities, which may contain competitive information.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Catalog\Api\Data\ProductInterface">
        <attribute code="stock_item" type="Magento\CatalogInventory\Api\Data\StockItemInterface">
            <resources>
                <resource ref="Magento_CatalogInventory::cataloginventory"/>
            </resources>
        </attribute>
    </extension_attributes>
</config>

In this example, we restrict the stock_item attribute to users with the Magento_CatalogInventory::cataloginventory permission.
Un-authenticated user issuing a GET /rest//V1/products/ request will receive product information like below.

{
  "sku": "tshirt1",
  "price": "20.00",
  "description": "New JSmith design",
  "extension_attributes": {
	"logo size": "small"
  },
  "custom_attributes": {
	"artist": "James Smith"
  }
}

Where as an authenticated user with the permission Magento_CatalogInventory::cataloginventory will receive the additional stock_item field like below,

{
  "sku": "tshirt1",
  "price": "20.00",
  "description": "New JSmith design",
  "extension_attributes": {
	"logo size": "small",
	"stock_item" : {
	  "status" : "in_stock"
	  "quantity": 70
	}
  },
  "custom_attributes": {
	"artist": "James Smith"
  }
}

Some examples of Magento 2 Extension Attributes:


Declare extension attribute:
Create one extension_attribute.xml file at your custom module like my module is Jrb_CustomExtensionAttribute with path like app/code/ Jrb/CustomExtensionAttribute/etc/extension_attribute.xml and keep below code

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

From above one we are going to extend our shipping information interface with an attribute. Its accessible from $order->getExtensionAttributes()->getJrbShippingAttribute().
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->getJrbShippingCharge(); // get custom attribute value

Thanks for visiting this article, hope you understand this article (‘Extension attributes in adobe commerce magento 2‘). You can also check our article How to add extension attribute in Magento2

Magento 2 Extension Attributes

One thought on “Magento 2 Extension Attributes

Leave a Reply

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