What is extension attributes in magento 2
How does extension attributes work?
How to use extension attributes in custom function in magento 2 ?
What is Extension Attributes ? Why do we need to use it?
- Magento has many existing entities : customer, catalog_product, order, customer_address, quote, tax, promotion…
- Some Entities like customer , catalog_product, customer_address are Entity-Attribute-Value (EAV) can add more information using custom attribute (by program or merchant) easy to add more.
- But some entities are not EAV. In magento 1, we need to add new column in existing tables for new information field => hard to control with version publish after
- Extension attributes is another way to add more information for existing entities (not EAV and EAV entities)
- EAV entities can also using it in some complexible case.
How to use Extension Attributes ?
- Find entity data want to add custom information . Example product Magento\Catalog\Api\Data\ProductInterface
- Entity need to implement extension attribute : Magento\Framework\Api\ExtensibleDataInterface and must define getExtensionAttributes() and setExtensionAttributes(*ExtensionInterface param)
- Create define module’s Extension attributes :
- Find the point need to set extension attribute and save info to custom field in existing entity. Can use plugin or events for it
How does Extension Attribute work?
- Existing entity has setter and getter for extension attribute:
- Extension attribute entity automatic generated in ‘generated’ folder, after config it in module need ro remove this folder to apply the change
- Example for product entity: Magento\Catalog\Api\Data\ProductExtension
- If entity of Extension attribute have not created in generated folder function getExtensionAttributes() return null => need to create Extension attribute entity and set it setExtensionAttributes(ExtensionInterface param)
You can read more here