An attribute set is a group of multiple individual product attributes that define the characteristics of the products. It is used every time while creating a new product in Magento 2 to bring all the attribute options to set during data entry which would be available to the customers.
While upgrading to the latest Magento version, migrating to Magento 2 or for custom purpose, you may require to create a bunch of attribute sets. Doing it manually through the Magento 2 backend requires tons of efforts and time. To ease and quick up the task, today I’ve come up with the custom code to create attribute set programmatically in Magento 2.
Script to create attribute set programmatically in Magento 2:
<?php namespace Vendor\Extension\Setup; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Catalog\Setup\CategorySetupFactory; use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory; class InstallData implements InstallDataInterface { private $attributeSetFactory; private $attributeSet; private $categorySetupFactory; public function __construct(AttributeSetFactory $attributeSetFactory, CategorySetupFactory $categorySetupFactory ) { $this->attributeSetFactory = $attributeSetFactory; $this->categorySetupFactory = $categorySetupFactory; } public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]); $attributeSet = $this->attributeSetFactory->create(); $entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY); $attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId); $data = [ 'attribute_set_name' => 'MyCustomAttribute', 'entity_type_id' => $entityTypeId, 'sort_order' => 200, ]; $attributeSet->setData($data); $attributeSet->validate(); $attributeSet->save(); $attributeSet->initFromSkeleton($attributeSetId); $attributeSet->save(); $setup->endSetup(); } }
That’s it!
You can also create attribute set in Magento 2 from the admin panel with the method given in guide to Magento 2 attribute set.
Thank You!