Tuesday 12 March 2019

Add New Field in Existing Custom Table in Drupal 8

Add new field in existing custom table in Drupal 8

To add new field you have to implement hook_update_N() in .install file.
hook_update_N()
  1. Can be used to update in minor version of a module.
  2. hook_update_N is named as modulename_update_number.
  3. number is composed of following rules
  • 1 or 2 digits for Drupal core compatibility (Drupal 8, 9, 10, etc.). This convention must be followed.
  • 1 digit for your module's major release version; for example, for 8.x-1.* use 1, for 8.x-2.* use 2, for Core 8.0.x use 0, and for Core 8.1.x use 1. This convention is optional but suggested for clarity.
  • 2 digits for sequential counting, starting with 01. Note that the x000 number can never be used: the lowest update number that will be recognized and run for major version x is x001.
  • Never renumber update functions. 
  • The numeric part of the hook implementation function is stored in the database to keep track of which updates have run, so it is important to maintain this information consistently.
Example: 
  • node_update_8001(): The first update for the Drupal 8.0.x version of the Drupal Core node module.
  • mymodule_update_8101(): The first update for your custom or contributed module's 8.x-1.x versions.
  • mymodule_update_8201(): The first update for the 8.x-2.x versions.
For More information Please see Hook_update_N() on Drupal.org
firstcustommodule.install

Add below line on the top of the file firstcustommodule.install file
use Drupal\Core\Database\Database;
Add below code in firstcustommodule.install file
/**
 * Implements hook_update_N
 */
function firstcustommodule_update_8001() {
  $status = [
    'description' => 'Company Status Active or inactive',
    'type' => 'int',
    'size' => 'tiny',
    'not null' => FALSE,
  ];
  $schema = Database::getConnection()->schema();
  $schema->addField('company_information', 'status', $status);
}

Save above file and now go to drush.
Run command drush updb as shown in below screenshot.






After running of this command successfully, table structure will look like as shown in screenshot.
New column "status" is available.










No comments:

Post a Comment