[Drupal] How to use hook_schema function in your own Drupal module

| | 1 min read

If you are a Drupal developer, you would often encounter a situation where your Drupal module needs to create a custom table automatically when enabled. If you are new to Drupal, Checkout How to create your own Drupal module to know how to do it. Drupal provides you this option using hook_schema. Read on to know how to use hook_schema in your Drupal module .

First of all, create a ".install" file inside your module.

Now, create the hook_schema function inside the .install file.

Here is a simple code for creating a simple hook_schema function.


function hook_schema() {
  $schema['sample_table'] = array(
    'description' => 'A table to store sample data',
    'fields' => array(
      'id' => array(
      'description' => 'Holds the id value',
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
      ),
      'name' => array(
        'description' => 'Holds the name value',
        'type' => 'varchar',
        'length' => '50',
        'not null' => TRUE,
      ),
    ),  
    'primary key' => array('id'), 
  );  
  return $schema;
}

The above schema function will create a table with just two columns.

The table will have table name 'sample_table', the columns will be 'id' and 'name'

Set the primary key for the table as mentioned in the above code.

Let us know if you have found this article useful

 

 

Zyxware is a leading Drupal development company with a team of high expertise in Drupal custom module development services since 2006.