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?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI 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?
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();
}
}
} ?>