1

I'm using Drupal 8.0.5. In my settings.php file I have defined an external database:

$databases['notificationsdb']['default'] = array (
  'database' => 'NotificationsDB',
  'username' => 'my_user_name',
  'password' => 'my_password',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

I have then created a custom form where I need values from the NotificationsDB database to populate a form fields. In my custom form class in the __constructor I created an instance of my Notification Client class:

public function __construct() {
        $this->_notificationClient = new NotificationsClient();
}

In my NotificationsClient class I have the following code:

public function __construct() {
        // Set the active database to notificationsdb
        \Drupal\Core\Database\Database::setActiveConnection('notificationsdb');
        $this->_db = \Drupal\Core\Database\Database::getConnection();
    }
public function __destruct() {
        // Set the active database back to the default
        \Drupal\Core\Database\Database::setActiveConnection('default');
        // https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!Database.php/function/Database%3A%3AsetActiveConnection/8
}

When I go to view my form I get the following error:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'notificationsdb.shortcut_set_users' doesn't exist: SELECT ssu.set_name AS set_name FROM {shortcut_set_users} ssu WHERE (ssu.uid = :db_condition_placeholder_0); Array ( [:db_condition_placeholder_0] => 1 ) in Drupal\shortcut\ShortcutSetStorage->getAssignedToUser() (line 103 of core/modules/shortcut/src/ShortcutSetStorage.php).

From what I can tell the Shortcuts module is trying to run some queries against the NotificationsDB. I'm guessing this is a timing issue. I'm also concerned with how Drupal handles multiple database connections.

1

In looking at the getConnections method closer you can pass it the $target and $key parameters directly and it will return a handle to the specified database.

$this->_db = \Drupal\Core\Database\Database::getConnection('default', 'notificationsdb');

This way you don't have to mess around with setting the active database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.