Using the following codes we can change the connection to an external database.

$database = Database::getConnection('', $database_key);    //'external'
$container = \Drupal::getContainer();
$container->set('database', $database);

However, when we want to save an entity we need to either use Node:: create or the entityTypeManager's create method as follows.

$node = \Drupal::entityTypeManager()->getStorage('node')->create( array(

        'type' => 'article',

        'title' =>'test',

        'body' => array(

            'value' =>'The body of the content',

            'format' => 'full_html',

As far as the entityTypeManager object is already initialized changing the database connection has no effects and the node will be saved in the default database again. So, is there a way to reinitialize the entityTypeManager or to reset the storage method so that it uses the second database?

Any helps will be appreciated. Thanks

  • 1
    Honestly, that seems like a bad idea. Is that another drupal site? What about depending services, saving an entity needs to invalidate cache tags, that would invalidate the cache tags on your current site most likely and so on. If you want to create nodes on another Drupal site, then I would strongly recommend to use some sort of (http-based) API
    – Berdir
    Jan 18, 2018 at 20:52
  • Yes, it's another Drupal site in which I want to use to keep the shared content between several Drupal sites. Since they are all on one server, I thought I just switch the databases but I believe you are right I better use the web services. Thanks @Berdir
    – Hedeshy
    Jan 22, 2018 at 10:37


Your Answer

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

Browse other questions tagged or ask your own question.