Drupal Custom Module when Create database table during installation


Assume that, your module needs the database tables for storing the module related data. In this tutorial, we’ll discuss the process of creating a table into the database during module installation. Your module needs a .install file, which helps your module to create required table when the module is first enabled and removed when the module is uninstalled. Also, you can update the database table based on your module’s updated version.

Creating .install file

In Drupal 7, a .install file is used to create database tables and fields, and inserting the data. .install file also is used to update the table structure and contents. .install file is a PHP file with different extension.

Create a .install file (mymodule.install) into the root directory of your module. Using this file, we’ll create a subscribers table into the database for storing the website subscriber’s data.

Define hook_schema()

hook_schema() holds an array structure for representing one or more tables and their related keys and indexes.

Define hook_schema for subscribers table and write the following code.

hook_schema() is invoked before hook_install() and after hook_uninstall() is invoked. If the tables declared by hook_schema(), then the tables will be automatically created when the module is first enabled and removed when the module is uninstalled.

Using hook_update_N()

hook_update_N function is used to add, update or delete database tables, fields or contents at the time of updating your module. For example, In the latest version of your module you want to add a new column at the subscribers table.

hook_update_N function would be the following.


Leave A Reply

Your email address will not be published.