Create custom table magento module

This tutorial explains how to create custom table magento module.The module create a table in the magento database using the install script.

With this module it create a table named ‘customer_form_table’ in the magento database with fields as shown below.

create_custom_table_magento_database

Step by step explanation.

  • File Structure
  • Enable module
  • Create config file
  • Create custom table – install script

File Structure

As the first step of creating the custom table create the following files.

create_custom_table_magento_module_file_structure

Enable Module

As the initial step of creating the module we need to enable the module.Create the xml file inside the etc/modules/Test_Customtable.xml folder and enter the following code.

<?xml version="1.0"?>
<config>
    <modules>
        <Test_Customtable>
            <active>true</active>
            <codePool>local</codePool>
        </Test_Customtable>
    </modules>
</config>

Create config file – magento module

In the config file add the following code.

<?xml version="1.0"?>
<config>
    <modules>
        <Test_Customtable>
            <version>0.1.0</version>
        </Test_Customtable>
    </modules>
    <global>
        <resources>
            <test_customtable_setup>
                <setup>
                    <module>Test_Customtable</module>
                </setup>
            </test_customtable_setup>
        </resources>
    </global>
</config>

Create custom table – install script

The following script create the custom table.

<?php

$installer = $this;

$installer->startSetup();

$installer->run("

DROP TABLE IF EXISTS `{$this->getTable('customer_form_table')}`;
CREATE TABLE `{$this->getTable('customer_form_table')}` (
  `log_id` int(11) unsigned NOT NULL auto_increment,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `admin_id` int(11) unsigned NOT NULL default '0',
  `customer_id` int(11) unsigned NOT NULL default '0',
  `terms_old` int(11) unsigned NOT NULL default '0',
  `terms_new` int(11) unsigned NOT NULL default '0',
  `limit_old` DECIMAL(10,5) NOT NULL default '0',
  `limit_new` DECIMAL(10,5) NOT NULL default '0',
  `available_old` DECIMAL(10,5) unsigned NOT NULL default '0',
  `available_new` DECIMAL(10,5) unsigned NOT NULL default '0',
  PRIMARY KEY (`log_id`),
  INDEX (customer_id),
  INDEX (admin_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

");

$installer->endSetup();

Now you have created the complete code. Login to the magento database and clear the cache.

If you have further queries please leave a reply.

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*