n Update an existing custom schema in Drupal 8 | 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 tutorial, we will see how to add field to custom schema in Drupal 8 without losing data using a hook_update_N().

Example how to use hook_update_N() :

<?php

use Drupal\Core\Database\Database;

/**
 * @param $sandbox
 */
function mymodule_update_90002(&$sandbox) {
  $spec = [
    'type' => 'varchar',
    'description' => "New Col",
    'length' => 20,
    'not null' => FALSE,
  ];
  $schema = Database::getConnection()->schema();
  $schema->addField('mymodule', 'newcol', $spec);
  $schema->addIndex('mymodule', 'newcol',['newcol'],$spec);

  return t('new col added to mymodule table.');
}

After this, running drush updb or running update.php from the admin interface should detect your hook_update_N() and it should add your new field.

 

 

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