0

I'm following this tutorial to create a new table inside the database.

From the tutorial, I've followed till Step 4. I can verify that a the new module is created after running php bin/magento setup:upgrade, but no table named greeting_message is created for me.

I guess, The database here refers to the database I created while Installing Magento. I've seen all the tables of the database from phpmyadmin but there is no database named greeting_message.

Where am I going Wrong?

InstallData.php

<?php


    namespace Learning\GreetingMessage\Setup;

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

    /**
     * @codeCoverageIgnore
     */
    class InstallData implements InstallDataInterface
    {

      /**
       * {@inheritdoc}
       * @SuppressWarnings(PHPMD.CyclomaticComplexity)
       * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
       * @SuppressWarnings(PHPMD.NPathComplexity)
       */
      public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
      {
        /**
         * Install messages
         */
        $data = [
             ['message' => 'Happy New Year'],
             ['message' => 'Marry Christams']
             ];
        foreach ($data as $bind) {
          $setup->getConnection()
        ->insertForce($setup->getTable('greeting_message'), $bind);
        }
      }
    }

InstallSchema.php

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Learning\GreetingMessage\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)
  {
    /**
     * Create table 'greeting_message'
     */
    $table = $setup->getConnection()
      ->newTable($setup->getTable('greeting_message'))
      ->addColumn(
                  'greeting_id',
                  \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                  null,
                  ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
                  'Greeting ID'
          )
      ->addColumn(
                  'message',
                  \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                  255,
                  ['nullable' => false, 'default' => ''],
          'Message'
          )->setComment("Greeting Message table");
    $setup->getConnection()->createTable($table);
  }
}
  • post your InstallData.php file of your module – Manthan Dave Jul 10 '17 at 9:10
  • It's same as mentioned on the page with prefix <?php. Added above. – kashish Jul 10 '17 at 9:56
  • so when you run command setup:upgrade - its not creating table ? – Manthan Dave Jul 10 '17 at 10:10
  • yes, it's not creating table. – kashish Jul 10 '17 at 10:11
  • did you checked any error in logs? – Suresh S Jul 10 '17 at 10:23
1

Please remove the entry Learning_GreetingMessage in setup_module table of the database used by Magento and then enter php bin/magento setup:upgrade command again in the root directory of Magento.

0

The script you have posted is a InstallData script. This will only add data to a current table and not create a new table. The standard approach here would be to create a script InstallSchema script that would then do the table creation.

Have a look through vendor/magento/module-catalog/Setup/InstallSchema.php to see how Magento does this but the basic idea is.

  1. Get the table name from the config,
  2. Add the table to the database,
  3. Add columns to the table,

The following is a "basic" example.

public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
    $installer = $setup;

    $installer->startSetup();

    /**
     * Create table 'catalog_product_entity'
     */
    $table = $installer->getConnection()
        ->newTable($installer->getTable('catalog_product_entity'))
        ->addColumn(
            'entity_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
            'Entity ID'
        )
        ->addColumn(
            'attribute_set_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['unsigned' => true, 'nullable' => false, 'default' => '0'],
            'Attribute Set ID'
        )
        ->addColumn(
            'type_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            32,
            ['nullable' => false, 'default' => 'simple'],
            'Type ID'
        )
        ->addColumn(
            'sku',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            64,
            [],
            'SKU'
        )
        ->addColumn(
            'has_options',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['nullable' => false, 'default' => '0'],
            'Has Options'
        )
        ->addColumn(
            'required_options',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['unsigned' => true, 'nullable' => false, 'default' => '0'],
            'Required Options'
        )
        ->addColumn(
            'created_at',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            null,
            ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
            'Creation Time'
        )
        ->addColumn(
            'updated_at',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            null,
            ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
            'Update Time'
        )
        ->addIndex(
            $installer->getIdxName('catalog_product_entity', ['attribute_set_id']),
            ['attribute_set_id']
        )
        ->addIndex(
            $installer->getIdxName('catalog_product_entity', ['sku']),
            ['sku']
        )
        ->addForeignKey(
            $installer->getFkName(
                'catalog_product_entity',
                'attribute_set_id',
                'eav_attribute_set',
                'attribute_set_id'
            ),
            'attribute_set_id',
            $installer->getTable('eav_attribute_set'),
            'attribute_set_id',
            \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
        )
        ->setComment('Catalog Product Table');
    $installer->getConnection()->createTable($table);
    $installer->endSetup();
}
  • I've also added InstallSchema.php. I've followed all steps of tutorial mentioned above. – kashish Jul 10 '17 at 10:30
0

To Create Table "greeting_message" First you need to create InstallSchema.php file

Try below code :

InstallSchema.php file.

<?php

namespace Vendor\ModuleName\Setup;

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

class InstallSchema implements InstallSchemaInterface
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $table = $setup->getConnection()->newTable(
            $setup->getTable('greeting_message')
        )->addColumn(
            'custom_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
            'Custom Id'
        )->addColumn(
            'message',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            [],
            'Message'
        )->setComment(
            'Greeting Message'
        );
        $setup->getConnection()->createTable($table);

        $setup->endSetup();
    }
}

installData.php file

<?php
namespace Vendor\ModuleName\Setup;

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

class InstallData implements InstallDataInterface {

    /**
     * 
     * Install Data in greeting_message table
     *   
     */
    public function install( ModuleDataSetupInterface $setup, ModuleContextInterface $context ) {
        $setup->startSetup();

        $tableName = $setup->getTable('greeting_message');

        if ($setup->getConnection()->isTableExists($tableName) == true) {
        $data = [
        [
            'custom_id' => '1',
            'message' => 'Happy New Year'
        ],
        [
             'custom_id' => '2',
            'message' => 'Marry Christams'
        ],
        ];
        foreach ($data as $bind) {
                $setup->getConnection()->insert($tableName,$bind);
            } 
        }
         $setup->endSetup();
    }
}

Basically InstallSchema is used for creating table and its structure And InstallData is used for insert data into table.

For more refrence refer this link - http://inchoo.net/magento-2/setup-scripts-magento-2/

  • I've already added both the files. You asked only for InstallData.php, so , I pasted it's output only. sry! – kashish Jul 10 '17 at 10:38
  • @kashish no worries , do one thing create separate module and copy both the file which i have added here and it will work for you – Manthan Dave Jul 10 '17 at 10:52
  • Is there anything wrong with my code? – kashish Jul 10 '17 at 10:57
  • @kashish well compare with my code , i always prefer code module as reference i have taken this code from magento core modules and used many times and its working well . – Manthan Dave Jul 10 '17 at 10:58
0
$ php bin/magento module:disable Learning_GreetingMessage

Now from Db table "setup_module" and remove entry "Learning_GreetingMessage"

Now enable and upgrade the magento

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

And now you can check the DB

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.