0

I am trying to create custom attribute set by using upgradeData script in magento 2, but it doesn't create.

Can anyone give me an advice?

1

Please find the code to create custom attribute set in Magento2 programmatically

We declare the namespace of our module to avoid conflicts around multiple modules and introduce more flexibility

namespace Namespace\Module\Setup;

 /*
*The below are the namespaces and and classes to be included inorder to create new custom attribute set 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\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]);
      /**
      *checking the current version of the module 
      *this function is implemented from  ModuleContextInterface
     */
    if(version_compare($context->getVersion(), '1.1', '<')) {

        $attributeSet = $this->attributeSetFactory->create();
        $entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY);
        $attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);
        $data = [
        'attribute_set_name' => 'Your_Custom_Attribute_Set', // define custom attribute set name here
        'entity_type_id' => $entityTypeId,
        'sort_order' => 200,
        ];
        $attributeSet->setData($data);
        $attributeSet->validate();
        $attributeSet->save();
        $attributeSet->initFromSkeleton($attributeSetId);
        $attributeSet->save();
    }
    }
} ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.