1

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?

0

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"/>
  • Thank's but I had to disable/enable the module before getting my code run, but the UpgradeData runs with your method – medmek Jan 28 at 10:40
0

Set required to true. This is because when attribute is required, it has a value all the time.

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.