How to create Install, Upgrade, Uninstall Script in Magento 2

Written by Payal Patel

Mar 19, 2021

How to create Install, Upgrade, Uninstall Script in Magento 2

Today, we will describe how to create an install, upgrade and uninstall script in Magento 2. In the previous tutorial, we saw how to create Block, Layouts and Templates in Magento 2. When you creating a module, sometimes you need to create a custom table and add some fields for this custom module. So first of all you need to create an Install script.

Now, we will learn an Install script with InstallSchema and InstallData.

Install Script: InstallSchema and InstallData

InstallSchema and InstallData classes will be run during the module installation.

Create InstallSchema.php file in the app/code/Dolphin/MyModule/Setup with the following code.

<?php

namespace Dolphin\MyModule\Setup;

class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface
{

    public function install(
        \Magento\Framework\Setup\SchemaSetupInterface $setup,
        \Magento\Framework\Setup\ModuleContextInterface $context
    ){
        $installer = $setup;
        $installer->startSetup();
        if (!$installer->tableExists('dolphin_mymodule_contact')) {
            $table = $installer->getConnection()->newTable(
                $installer->getTable('dolphin_mymodule_contact')
            )
                ->addColumn(
                    'id',
                    \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                    null,
                    [
                        'identity' => true,
                        'nullable' => false,
                        'primary'  => true,
                        'unsigned' => true,
                    ],
                    'ID'
                )
                ->addColumn(
                    'name',
                    \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    255,
                    ['nullable => false'],
                    'Name'
                )
                ->addColumn(
                    'email',
                    \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    255,
                    [],
                    'Email'
                )
                ->addColumn(
                    'phone_no',
                    \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                    null,
                    [],
                    'Phone Number'
                )
                ->addColumn(
                    'message',
                    \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    '64k',
                    [],
                    'Message'
                )
                ->addColumn(
                    'created_at',
                    \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                    null,
                    ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
                    'Created At'
                )->addColumn(
                    'updated_at',
                    \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                    null,
                    ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
                    'Updated At')
                ->setComment('Dolphin Contact Table');
            $installer->getConnection()->createTable($table);

            $installer->getConnection()->addIndex(
                $installer->getTable('dolphin_mymodule_contact'),
                $setup->getIdxName(
                    $installer->getTable('dolphin_mymodule_contact'),
                    ['name', 'email', 'message'],
                    \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
                ),
                ['name', 'email', 'message'],
                \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
            );
        }
        $installer->endSetup();
    }
}

The getTable function in the preceding code simply ensures that the table name is formatted correctly. The Install() method is with two arguments SchemaSetupInterface and ModuleContextInterface. The SchemaSetupInterface provides many functions to interact with the database server. The only method in the ModuleContextInterface is getVersion(), which returns the current version of your module.

Now you can go into the database and check your table with columns: id, name, email, phone_no, ….

Create InstallData.php file in the app/code/Dolphin/MyModule/Setup with the following code.

<?php

namespace Dolphon\MyModule\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
    protected $_contactFactory;

    public function __construct(\Dolphon\MyModule\Model\ContactFactory $contactFactory)
    {
        $this->_contactFactory = $contactFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $data = [
            'name'    => "John",
            'email'	  => "john@example.com",
            'phone_no'=> '0123456789',
            'message' => 'Text Message'
        ];
        $contact = $this->_contactFactory->create();
        $contact->addData($data)->save();
    }
}

InstallData run after the InstallSchema.

Upgrade Script: UpgradeSchema and UpgradeData

UpgradeSchema and UpgradeData both files will be run during the module installed or upgraded. But these files are run every time when the module upgraded. So we will change the setup_version attribute in module.xml file.

Now, go into the app/code/Dolphin/MyModule/etc folder and open module.xml file. Check setup_version and change if you have 1.0.0 then update 1.0.0 to 1.0.1 or something like that. Check the following source code.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Dolphin_MyModule" setup_version="1.0.1">
    </module>
</config>

Create UpgradeSchema.php file in the app/code/Dolphin/MyModule/Setup with the following code.

<?php

namespace Dolphin\MyModule\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class UpgradeSchema implements UpgradeSchemaInterface
{
    public function upgrade(
        SchemaSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $installer = $setup;
        $installer->startSetup();
        if(version_compare($context->getVersion(), '1.0.1', '<')) {
            $installer->getConnection()->addColumn(
                $installer->getTable('dolphin_mymodule_contact'),
                'company',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'nullable' => true,
                    'length' => '255',
                    'comment' => 'company',
                    'after' => 'message'
                ]
            );
        }
        $installer->endSetup();
    }
}

The upgrade() method will be run every time the module upgraded and compare the version.

Create UpgradeData.php file in the app/code/Dolphin/MyModule/Setup with the following code.

<?php

namespace Dolphin\MyModule\Setup;

use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class UpgradeData implements UpgradeDataInterface
{
    protected $_contactFactory;

    public function __construct(\Dolphin\MyModule\Model\ContactFactory $contactFactory)
    {
        $this->_contactFactory = $contactFactory;
    }

    public function upgrade(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        if (version_compare($context->getVersion(), '1.0.1', '<')) {
            $data = [
                'name'    => "Jolly",
                'email'	  => "jolly@example.com",
                'phone_no'=> '1234567890',
                'message' => 'Text Message'
                'company' => 'Company Name'
            ];
            $contact = $this->_contactFactory->create();
            $contact->addData($data)->save();
        }
    }
}

Uninstall Script:

If you need to remove the table then you create Uninstall.php file in the app/code/Dolphin/MyModule/Setup with the following code.

<?php

namespace Dolphin\MyModule\Setup;

use Magento\Framework\Setup\UninstallInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class Uninstall implements UninstallInterface
{
    public function uninstall(
        SchemaSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $installer = $setup;
        $installer->startSetup();

        $installer->getConnection()->dropTable($installer->getTable('dolphin_mymodule_contact'));

        $installer->endSetup();
    }
}

We hope our guide is very effective for you. If any questions, please feel free to leave a comment below. In the next tutorial, we will help you with how to create, drop or other operations using Declarative Schema.

Payal Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP