Magento 2 how to save custom field added in the form of customer group?
Extension attributes mechanism should be used in this case. It allows extension of core APIs by 3rd party modules. Generic steps for enabling new extension attribute:
- Declare extension attribute as described in the official docs. After clearing
var
and running<project_root>/bin/magento setup:di:compile
, corresponding setter and getter for this new attribute should appear in\Magento\Customer\Api\Data\GroupExtensionInterface
(this interface is auto-generated) - Write plugins for
\Magento\Customer\Api\GroupRepositoryInterface::save
,\Magento\Customer\Api\GroupRepositoryInterface::getById
(and any other service methods as necessary) to save/load new attribute. As an extension developer, only you know where this attribute should be stored, may be any table. See\Magento\Downloadable\Model\Plugin\AroundProductRepositorySave::aroundSave
as an example - If you need to make this attribute visible in collection (to make it searchable/filterable), declare
join
node. If not then just skip this - Access your custom attribute as:
$customerGroup->getExtensionAttributes()->getMyAttribute()
, wherecustomerGroup
implements\Magento\Customer\Api\Data\GroupInterface
.setMyAttribute()
can be used as well
Below is the example of configuration which should be put to VendorName/ModuleName/etc/extension_attributes.xml
<?xml version="1.0"?>
<config>
<extension_attributes for="Magento\Customer\Api\Data\GroupInterface">
<!--Data interface can be used as a type of attribute, see example in CatalogInventory module-->
<attribute code="name_of_attribute" type="string">
<resources>
<resource ref="VendorName_ModuleName::someAclNode"/>
</resources>
<!--Join is optional, only if you need to have added attribute visible in groups list-->
<join reference_table="table_where_attribute_is_stored" reference_field="group_id_field_in_that_table" join_on_field="group_id">
<field>name_of_added_attribute_field_in_that_table</field>
</join>
</attribute>
</extension_attributes>
</config>
Don't forget that a module needs a register.php
file in it, and you must use bin/magento module:enable VendorName_ModuleName
before it will show up!