Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidjguru/7533caf70d8256f7f540bfdda4f4e30c to your computer and use it in GitHub Desktop.
Save davidjguru/7533caf70d8256f7f540bfdda4f4e30c to your computer and use it in GitHub Desktop.
Drupal 8: Adding new fields in the database (install / uninstall)
// Context: In a custom module, within the .install file
// Doing tasks on the installation.
// Looking for a field and create if not exist.
// We'll delete this field in the uninstallation process.
// We're using a pair of basic Drupal hooks: install and uninstall.
/**
* Implements hook_install().
*/
function your_custom_module_install() {
// Get the connection and the database schema.
$connection = \Drupal::service('database');
$schema = $connection->schema();
// Test if the table 'Comment' exist or not.
if ($schema->tableExists('comment')){
// Test if the field 'extra' exist or not.
if(!($schema->fieldExists('comment','extra'))) {
// Build the field definition.
$field_definition = [
'description' => 'Newly created Extra Field.',
'type' => 'int',
'not null' => TRUE,
'default' => 1,
];
// Adding the new field if the field not exist.
$schema->addField('comment', 'extra', $field_definition);
// Set a new message.
\Drupal::logger('your_custom_module')->notice('Created field Extra');
}
}
}
/**
* Implements hook_uninstall().
*/
function your_custom_module_uninstall() {
// Get the connection and the database schema.
$connection = \Drupal::service('database');
$schema = $connection->schema();
// Test if the table 'Comment' exist or not.
if ($schema->tableExists('comment')) {
// Test if the field 'extra' exist or not.
if ($schema->fieldExists('comment', 'extra')) {
// If exist then delete the field.
$schema->dropField('comment', 'extra');
// Set a new message.
\Drupal::logger('your_custom_module')->notice('Field Extra deleted.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment