6 December, 2023
Custom Attribute Group in Magento 2

Creating Custom Attribute Group & Product Attribute Magento 2 via upgradeData.php

Attribute & Attribute Group:

Attributes are the most powerful features in Magento. An attribute defines a character and informs about the features of a product. Attribute group is nothing but a combination of multiple attributes. It will help you to group some attributes under a product tab in Magento backend while an attributes set is a set of attribute groups.

Here is a Tree form for better understanding:

Custom Attribute

Let us see how we can add custom attributes and attribute group in Magento 2.

Why via upgradeData:

If you want to insert any table related data (like attributes/attributeset/attibutegroup) after the module installation, go for upgradeData.


/*
* Declare the namespace of the module to avoid conflicts around multiple modules and introduce more flexibility
*/


namespace Namespace\Modulename\Setup;

 /*
*The below are the namespaces and and classes to be included inorder to create new custom attributes and custom attibute groups programatically
*/

use Magento\Eav\Setup\EavSetup; 
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Catalog\Setup\CategorySetupFactory;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;

/*
* UpgradeDataInterface brings the ‘upgrade’ method which must be implemented
*/
class UpgradeData implements UpgradeDataInterface
{
 	private $eavSetupFactory;
	private $attributeSetFactory;
	private $attributeSet;
	private $categorySetupFactory;
   	


public function __construct(EavSetupFactory $eavSetupFactory, AttributeSetFactory $attributeSetFactory, CategorySetupFactory $categorySetupFactory )
    	{
        		$this->eavSetupFactory = $eavSetupFactory; 
        		$this->attributeSetFactory = $attributeSetFactory; 
        		$this->categorySetupFactory = $categorySetupFactory; 
    	} 
	
 public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
 {
          $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);


    /**** Adding custom attribute group Default attribute set**/ 

      /**
      *checking the current version of the module 
      *this function is implemented from  ModuleContextInterface
     */

	if(version_compare($context->getVersion(), '1.2', '<'))
    {
		$categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
		$entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY);
                $attributeSetId = $categorySetup->getAttributeSetId($entityTypeId, 'default'); 

		/* you can either use this also 
		$attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);  
		*/

                
		$autosettingsTabName = 'custom_attribute_group1';
		$categorySetup->addAttributeGroup($entityTypeId, $attributeSetId, $autosettingsTabName, 60);

						}

  /*** Adding attribute group to CUSTOM atribute set ********/

	if(version_compare($context->getVersion(), '1.3', '<'))
	 {
		$categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
		$entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY);
                                     
                                   /*Dining the Custom attribute set to add attibute group */
		$attributeSetId = $categorySetup->getAttributeSetId($entityTypeId, 'custom_attribute_set');
		$autosettingsTabName = 'custom_attribute_group2';
		$categorySetup->addAttributeGroup($entityTypeId, $attributeSetId, $autosettingsTabName, 60);

						}



  /**** Adding custom Product Attribute **/ 

	if(version_compare($context->getVersion(), '1.4', '<'))
 {
		$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->removeAttribute(\Magento\Catalog\Model\Product::ENTITY,'your_custom_attribute');
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,  'your_custom_attribute',   /* Custom Attribute Code */
            [
                'group' => 'Product Details',/* Group name in which you want 
                                              to display your custom attribute */
                'type' => 'int',/* Data type in which formate your value save in database*/
                'backend' => '',
                'frontend' => '',
                'label' => 'Your Custom Attribute Label', /* lablel of your attribute*/
                'input' => 'select',
                'class' => '',
                'source' => 'ModuleNameSpace\YourModuleName\Model\Config\Source\Options',
                                /* Source of your select type custom attribute options*/
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                                    /*Scope of your attribute */
                'visible' => true,
                'required' => true,
                'user_defined' => false,
                'default' => '',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => true,
                'unique' => false
            ]
        );
    }
} 
} 

Add the above code to upgradeData.php under app/code/namespace/module/setup and update the version in module.xml under app/code/namespace/module/etc.

Note: The setup version has to be updated as per your current version (This is just a model)

Upgrade the module setup in Magento 2 using ‘upgrade’ command via CLI and see your custom product attribute and the custom attribute groups have been created.

Alex Sam is a digital marketer by choice & profession. He munches on topics relating to technology, eCommerce, enterprise mobility, Cloud Solutions and Internet of Things. His other interests lies in SEO, Online Reputation Management and Google Analytics. Follow Me Socially: Habr , Dev.to & Viblo .

Leave a Reply

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