0

I want to add product attributes programmatically. I did for one attribute and I want to add another attribute. It is not working when I wrote the code like below :

class InstallData implements InstallDataInterface
{
private $eavSetupFactory;

public function __construct(EavSetupFactory $eavSetupFactory)
{
    $this->eavSetupFactory = $eavSetupFactory;
}

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
    $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
    $eavSetup->addAttribute(
        \Magento\Catalog\Model\Product::ENTITY,
        'sample_attribute',
        [
            'type' => 'text','backend' => '','frontend' => '','label' => 'Sample Atrribute',
            'input' => 'text',
            'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
            'visible' => true,
            'required' => true,
            'user_defined' => false,'default' => '','visible_on_front' => false,
            'used_in_product_listing' => true,
            'unique' => false,
            'apply_to' => ''
        ]
        );
    $eavSetup->addAttribute(
        \Magento\Catalog\Model\Product::ENTITY,
        'sample_attribute1',
        [
            'type' => 'text',
            'backend' => '','frontend' => '','label' => 'Sample Atrribute',
            'input' => 'text',
            'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
            'visible' => true,'required' => true,'user_defined' => false,
            'default' => '',
            'visible_on_front' => false,
            'used_in_product_listing' => true,
            'unique' => false,
            'apply_to' => ''
        ]
    );
}
}

2 Answers 2

0

You are correct that you use data (and not schema), but as mentioned in the other answer, you have to create a file called UpgradeData.php. InstallData.php is only used when the module is installed for the first time.

This question & answer should work as a reference: Magento 2 UpgradeData doesn't work

0

In this case you need UpgradeSchema instead, InstallData is used when you install module for the first run and aims to insert data into database.

For more information here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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