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?

asked Oct 21, 2017 at 17:50

4 Answers 4

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"/>
Piyush
5,9249 gold badges35 silver badges67 bronze badges
answered Feb 8, 2018 at 5:44
1
  • Thank's but I had to disable/enable the module before getting my code run, but the UpgradeData runs with your method Commented Jan 28, 2019 at 10:40
0

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

0
0

I believe "default" is an invalid property for this script. All the valid properties can be found at: \Magento\Catalog\Model\ResourceModel\Setup\PropertyMapper

answered Mar 16, 2022 at 15:56
0

Try setting required to true

'required' => false

and (I highly recommend this) being strict with your value type, that being said try assigning a real integer to your default value like so

'default' => 1

answered Aug 24, 2022 at 3:16

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.