Magento 2 setup Upgrade scripts


  1. Under your Magento 2 module > inside the directory “Setup”
    (Create Magento 2 Module, Magento 2 install scripts)
    Create a new file: “UpgradeData.php” with the below content.

    
    <?php
    namespace Magleaks\Catalog\Setup;
    
    use Magento\Catalog\Model\Product;
    use Magento\Eav\Setup\EavSetupFactory;
    use Magento\Framework\Setup\ModuleContextInterface;
    use Magento\Framework\Setup\ModuleDataSetupInterface;
    use Magento\Framework\Setup\UpgradeDataInterface;
    
    class UpgradeData implements UpgradeDataInterface
    {
        /**
         * EAV setup factory
         *
         * @var EavSetupFactory
         */
        private $eavSetupFactory;
    
        /**
         * Init
         *
         * @param EavSetupFactory $eavSetupFactory
         */
        public function __construct(EavSetupFactory $eavSetupFactory)
        {
            $this->eavSetupFactory = $eavSetupFactory;
        }
    
        /**
         * @param ModuleDataSetupInterface $setup
         * @param ModuleContextInterface   $context
         */
        public function upgrade(
            ModuleDataSetupInterface $setup,
            ModuleContextInterface $context
        ) {
            $dbVersion = $context->getVersion();
            /** @var EavSetup $eavSetup */
            $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
    
            if (version_compare($dbVersion, '2.0.1', '<')) { // update an existing product attribute to add as soring options
                $eavSetup->updateAttribute(
                    Product::ENTITY,
                    'name',
                    'used_for_sort_by',
                    false
                );
            }
        }
    }
    
    
  2. Update the setup_version of your module in “etc/module.xml” file in your Module.

    
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
        <module name="Magleaks_Catalog" setup_version="2.0.1"/>
    </config>
    
    
  3. Go to your Magento 2 root folder from your terminal and run

    
    bin/magento setup:upgrade
    

Leave a Reply

  • (will not be published)