Tuesday 12 March 2019

Create Custom Table for custom module

To create custom table in Drupal, hook_schema is to use in .install file.
Create a custom table with hook_schema which having below fields.
company_id, company_name, company_email, company_telephone, company_address.

In Drupal 7
firstcustommodule.install
<?php

function firstcustommodule_schema() {
  $schema = array();
  $schema['company_information'] = array(
    'description' => 'Company Information',
    'fields' => array(
    'company_id' => array(
      'description' => 'Unique Company Id',
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
'company_name' => array(
  'description' => 'Company Name',
  'type' => 'varchar',
  'length' => 255,
),
'company_email' => array(
  'description' => 'Company Email',
  'type' => 'varchar',
  'length' => 255,
),
'telephone' => array(
  'description' => 'Telephone No of company',
  'type' => 'varchar',
  'length' => 255,
),
'address' => array(
  'description' => 'Address of company',
  'type' => 'varchar',
  'length' => 255,
),
    'primary key' => array('company_id'),
  );
  return $schema;

}

In Drupal 8 
<?php

function firstcustommodule_schema() {
  // Schema for company_information table
  $schema['company_information'] = [
'description' => 'Store company information such as company_id, name, email, telephone, address, timestamp',
'fields' => [
  'company_id' => [
    'description' => 'The primary identifier for the company.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
  ],
  'company_name' => [
    'description' => 'Company Name',
    'type' => 'varchar',
'length' => 64,
    'not null' => TRUE,
    'default' => '',
  ],
  'company_email' => [
    'description' => 'Company Email',
    'type' => 'varchar',
'length' => 64,
    'not null' => TRUE,
    'default' => '',
  ],
  'company_address' => [
    'description' => 'Company Address',
    'type' => 'varchar',
'length' => 64,
    'not null' => FALSE,
    'default' => '',
  ],
  'company_telephone' => [
    'description' => 'Company Telephone',
'type' => 'varchar',
'length' => 64,
'not null' => FALSE,
'default' => '',
  ],
  'created' => [
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Timestamp for when company was created.',
  ],
],
'primary key' => ['company_id'],
'indexes' => [
  'company_id' => ['company_id'],
  'company_name' => ['company_name'],
],
  ];
  return $schema;

}
Disable module and then enable it.
Now "company_information" table will be available in database with the structure as shown in screenshot.
This table having 6 fields.
In this structure, Created indexes are available.

















No comments:

Post a Comment