How To Create Custom Product Attribute Set From Installer In Magento 2

How To Create Custom Product Attribute Set From Installer In Magento 2- Here I am going to explain you how to create custom product attribute set from installer. If you want to create a custom product attribute set then make a installer file “InstallData.php” in Vendor\CustomModule\Setup and then add following code snippet.

<?php

namespace Vendor\ModuleName\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Catalog\Setup\CategorySetupFactory;

class InstallData implements InstallDataInterface
{

    private $attributeSetFactory;
    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); // Default attribute set Id
        $data = [
            'attribute_set_name' => 'Custom_Product_attribute_set', // custom attribute set name
            'entity_type_id' => $entityTypeId,
            'sort_order' => 50,
        ];
        $attributeSet->setData($data);
        $attributeSet->validate();
        $attributeSet->save();
        $attributeSet->initFromSkeleton($attributeSetId)->save(); // based on default attribute set
    }
}

Now in this way you can create custom product attribute set.

. . .

Ask a Feature