Drupal 7 – Insert database record on module installation

We could write custom module and use the hook_schema() to create new database table. The following <module>.install file will create a table called eureka_variables.

<?php
/**
 * Implements hook_schema().
 */
function <module>_schema() {
  $schema = array();

  $schema['eureka_variables'] = array(
    'description' => t('The table who stores the Eureka variables.'),
    'fields' => array(
      'id' => array(
        'description' => t('The primary identifier.'),
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'variable_key' => array(
        'description' => t('The Eureka variable key.'),
        'type' => 'varchar',
        'length' => '25',
        'not null' => TRUE
      ),
      'variable_value' => array(
        'description' => t('The Eureka variable value.'),
        'type' => 'varchar',
        'length' => '25',
        'not null' => TRUE
      ),
    ),
    'primary key' => array('id'),
  );

  return $schema;
}

 

If you want to insert some default key value pairs after the module is installed. Append the following the hook_install() after the hook_schema().

/**
 * Implements hook_install().
 */
function <module>_install() {
  $red = new stdClass();
  $red->variable_key = 'COLOR';
  $red->variable_value = 'RED';
  drupal_write_record('eureka_variables', $red);
  
  $yellow = new stdClass();
  $yellow->variable_key = 'COLOR';
  $yellow->variable_value = 'YELLOW';
  drupal_write_record('eureka_variables', $yellow);
  
  $green = new stdClass();
  $green->variable_key = 'COLOR';
  $green->variable_value = 'GREEN';
  drupal_write_record('eureka_variables', $green);
  
  $blue = new stdClass();
  $blue->variable_key = 'COLOR';
  $blue->variable_value = 'BLUE';
  drupal_write_record('eureka_variables', $blue);
  
  $violet = new stdClass();
  $violet->variable_key = 'COLOR';
  $violet->variable_value = 'VIOLET';
  drupal_write_record('eureka_variables', $violet);
  
  $black = new stdClass();
  $black->variable_key = 'COLOR';
  $black->variable_value = 'BLACK';
  drupal_write_record('eureka_variables', $black);
  
  $white = new stdClass();
  $white->variable_key = 'COLOR';
  $white->variable_value = 'WHITE';
  drupal_write_record('eureka_variables', $white);
}

 

Done =)

Reference:

3 thoughts on “Drupal 7 – Insert database record on module installation”

Leave a reply to ykyuen Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.