• Bilal Malik

Create Tabel In Magento 2

Updated: Aug 20

Prerequisite for follow this tutorial [optional]

I already created a boilerplate module, which makes easy to follow this tutorial. It is optional, you can follow with your own module too.

  1. Download module repository from bitbucket

  2. Extract downloaded folder

  3. Copy Bilal folder into your <magento-root>/app/code/

After run the below commands to enable module

$ php bin/magento module:enable Bilal_Cruddemo
$ php bin/magento setup:upgrade

Once you’ve run the above, you should be able to access the following URL in your system


and see the rendered text

Hello alert/index.phtml

Create Table

Whenever you want to create new table, you should write create table logic in InstallSchema.php


 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.

namespace Bilal\Cruddemo\Setup;

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

 * @codeCoverageIgnore
class InstallSchema implements InstallSchemaInterface
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
        $installer = $setup;


         * Create table 'crud_test_emp1'
        $table = $installer->getConnection()->newTable(
            ['identity' => true, 'nullable' => false, 'primary' => true],
            'primary key'
            ['nullable' => false],
            'Name of employee'
            ['nullable' => false, 'default' => '0'],
            'Age of employee'
            'crud test table'



Delete record of the cruddemo module from the setup_module table.

DELETE FROM `setup_module` WHERE `module`='Bilal_Cruddemo';

InstallSchema.php only execute while run setup upgrade, while setup upgrade Magento look into setup_module table, whether the extension new or exist, if exist, it skips the InstallSchema execution that’s why we delete the records, now Magento think “it is new module so we need to execute InstallSchema.php”

run the below command

php bin/magento setup:upgrade

That’s it!

Check the database, we have our newly created table.

Please carry same source code to follow the next tutorial.

#crud #InstallSchema #magento2 #tableschema


Recent Posts

See All

What is requireJS AMD in Magento2

Simply we can say, below format is the AMD module. define(['jquery'] , function ($) { return function () {}; }); Module Vs AMD module 1. Javascript Module Pattern (function () { this.myGlobal =

©2020 by Bilal Usean. Proudly created with Wix.com