n Drupal 8 - Store data in a custom table | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

in this post, I'll show you how to create a custom table to store data in the database.

to create your custom table you need minimum the hook_schema() method in the mymodule.install file. also I use hook_install(), which is called after the hook_schema() to store some examples in our mymodule Table.

mymodule.install

<?php

/**
 *  hook_install()
 */
function mymodule_install() {
  $values = [
    [
      'name' => 'Jhon',
      'age' => 30,
      'uid' => 1,
    ],
    [
      'name' => 'Jan',
      'age' => 28,
      'uid' => 1,
    ],
  ];
  $database = \Drupal::database();
  $query = $database->insert('mymodule')->fields(['name', 'age', 'uid']);
  foreach ($values as $developer) {
    $query->values($developer);
  }
  $query->execute();

}

/**
 * hook_schema()
 */
function mymodule_schema() {

  $schema['mymodule'] = array(
    'description' => 'Store developers',
    'fields' => array(
      'did' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique developer ID.',
      ),
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => "Creator user's {users}.uid",
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Name of the developer.',
      ),
      'age' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => 'The age of the developer in years.',
      ),
    ),
    'primary key' => array('did'),
    'indexes' => array(
      'name' => array('name'),
      'age' => array('age'),
    ),
  );
  return $schema;
}

Demo

custom table in drupal 8

 

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook