Skip to content

Instantly share code, notes, and snippets.

@laradevitt
Last active June 17, 2023 14:17
Show Gist options
  • Save laradevitt/8a9f07860f5bd3e088c6 to your computer and use it in GitHub Desktop.
Save laradevitt/8a9f07860f5bd3e088c6 to your computer and use it in GitHub Desktop.
(Drupal 8) Create a table in a database other than the default during module installation. Database must already be specified in settings.php.
<?php
/**
* @file
* Install, update and uninstall functions for the d8module module.
*/
function d8module_schema_otherdb() {
$schema['mytable'] = array(
'description' => 'My table description',
'fields' => array(
'myfield' => array(
'description' => 'My field description',
'type' => 'serial',
'size' => 'medium',
'not null' => TRUE,
'unsigned' => TRUE,
),
),
'primary key' => array('myfield'),
);
return $schema;
}
/**
* Implements hook_install().
*/
function d8module_install() {
\Drupal\Core\Database\Database::setActiveConnection('otherdb');
$connection = \Drupal\Core\Database\Database::getConnection();
$schema = d8module_schema_otherdb();
foreach ($schema as $name => $table) {
$connection->schema()->createTable($name, $table);
}
\Drupal\Core\Database\Database::setActiveConnection();
}
/**
* Implements hook_uninstall().
*/
function d8module_uninstall() {
\Drupal\Core\Database\Database::setActiveConnection('otherdb');
$connection = \Drupal\Core\Database\Database::getConnection();
$schema = d8module_schema_otherdb();
foreach ($schema as $name => $table) {
$connection->schema()->dropTable($name);
}
\Drupal\Core\Database\Database::setActiveConnection();
}
@RoloDMonkey
Copy link

Great example, but shouldn't line 32 be:

$schema = d8module_schema_otherdb();

@laradevitt
Copy link
Author

@RoloDMonkey - Yup. Thanks!

@solody
Copy link

solody commented Oct 28, 2021

Tested in drupal9, it's not working.

@artemvd
Copy link

artemvd commented May 2, 2022

Works with Drupal 9.3.12. @solody are you sure you have used the correct database name instead of otherdb?

@MahmoudSayed96
Copy link

Thank you, saved my time worked with Drupal 9.5.9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment