Install Data is not executed in magento 2
-
14-04-2021 - |
Question
I am trying to create a category attribute:
This is my file form Vendor/Module/Setup:
use Magento\Catalog\Model\Category;
use Magento\Catalog\Setup\CategorySetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $categorySetupFactory;
public function __construct(CategorySetupFactory $categorySetupFactory)
{
$this->categorySetupFactory = $categorySetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
$categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
$categorySetup->addAttribute(
Category::ENTITY,
'content_category_page',
[
'type' => 'int',
'label' => 'Content Page',
'input' => 'select',
'sort_order' => 100,
'source' => 'Magento\Catalog\Model\Category\Attribute\Source\Page',
'global' => 2,
'visible' => true,
'required' => true,
'user_defined' => false,
'default' => null,
'group' => 'General Information',
'backend' => ''
]
);
$installer->endSetup();
}
}
The current version of the module is 1.0.1, so I increased it to 1.0.2 and run the setup:upgrade
. After the module is updated to version 1.0.2 in the setup_module
table, but my InstallData is not executed and the attribute is missing . Not sure what I am doing wrong here? Would you please advice ?
Thnx
Solution
You need to create an UpgradeData class in Setup. Here is an example
<?php
namespace Custom\Module\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
class UpgradeData implements UpgradeDataInterface
{
/**
* UpgradeData constructor.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(
EavSetupFactory $eavSetupFactory
) {
$this->eavSetupFactory = $eavSetupFactory;
}
/**
* @param ModuleDataSetupInterface $setup
* @param ModuleContextInterface $context
*/
public function upgrade(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
/** @var EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
if (version_compare($context->getVersion(), '1.0.2', '<')) {
// upgrade attribute data here
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange