4

What I am trying to do is to save a copy of a node object after it is inserted into another Drupal database.

As it can be seen in the following piece of code, my idea is to change the database after a node is inserted. Make a copy of the node and save it. Then, return to the default database.

However, seems like entity storage manager is set to default database in node save function. Therefore, the node is getting saved inside the default database again.

//... mymodule_node_insert

$node = Node::load($id);
\Drupal\Core\Database\Database::setActiveConnection('external');
$db = \Drupal\Core\Database\Database::getConnection();

// save the node in the shared database
// Create node object with attached file.
$sharedNode = Node::create([
    'type'        => $node->getType();,
    'title'       => $node->getTitle();,
    'body_text'   => $node->get('body')->value,
]);
$sharedNode->save();

\Drupal\Core\Database\Database::setActiveConnection();

How can I make this work? Am I following a correct logic?

Any helps would be appreciated. Thanks

2

This seems similar to Database::setActiveConnection not working as expected?. Perhaps the Node object you've instantiated before switching the connection is still going to hold on to the old db settings as the source to save.

The DatabaseSwitcher class (found in the above posted question, just under the accepted answer by the original poster) may be an effective way for you to switch the container context in a way that will allow your already instantiated Node object to save in your external DB:

//... mymodule_node_insert

$node = Node::load($id);
$db_switcher = new DatabaseSwitcher();
$db_switcher->changeToDifferentDb('external');

// save the node in the shared database
// Create node object with attached file.
$sharedNode = Node::create([
    'type'        => $node->getType();,
    'title'       => $node->getTitle();,
    'body_text'   => $node->get('body')->value,
]);
$sharedNode->save();

$db_switcher->changeToDefaultDb(); 

Hope this works for you!

  • Thanks, great idea! I was really optimistic about this answer. Although, it does not work for nodes. After investing a bit time, I have found the reason. Nodes are getting saved through entity manager. So, just changing the database in the container is not enough. However, your answer showed me the path. Thanks – Hedeshy Jan 17 '18 at 15:30
  • Now, the question is how can I change the entity.manager inside the container so this class works also for entities? – Hedeshy Jan 17 '18 at 16:48

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.