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.

 

 

Comments

Add new comment

Restricted HTML

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

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

Web Posts

Search

Page Facebook