Magento – Set default value for attribute in Setup Script in Magento 2

attributescategorycategory-attributeeavmagento2

I have created install script to add an attribute to category.

Default value has to be set, thus 'default' => '1', is used.

InstallData.php file:

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
    /** @var EavSetup $eavSetup */
    $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
    $eavSetup->addAttribute(
        Category::ENTITY,
        'my_attr',
        [
            'type' => 'int',
            'label' => 'My',
            'input' => 'select',
            'default' => '1',
            'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
            'required' => false,
            'sort_order' => 100,
            'group' => 'General',
        ]
    );
}

The problem is that later when I use $cat->getMyAttr() I can get this only when I have set it to true or false in admin panel and saved settings. Otherwise I get just null.

In other words default value is not being set during setup of the module.
How to set default value that will be set to all the categories with setup script?

Best Answer

This is because according to Magento your module data is already installed and it doesn't update your changes in the InstallData file unless you change your module version. Here's the solution:

Go to your module directory and look for module.xml file in etc folder and simply change the setup version number so that the Magento knows that it has to update the data. Obviously, the setup version will be higher than current. For ex, if it's 1.0.1 then change it to 1.0.2

<module name="yourmodule_name" setup_version="1.0.1"/>