Drupal 8 Transaction with entities

Events happening in the community are now at Drupal community events on www.drupal.org.
Posted by vacho on August 25, 2017 at 12:59pm

Is there any kind of transactional mechanism for Entities (D8), similar to SQL transactions, so that I could conveniently rollback in case of an error?

Comments

Hi, Vacho, when you say error

Posted by ikit-claw on August 25, 2017 at 1:22pm

Hi, Vacho, when you say error do you mean as entering the wrong information or system error?

Thanks

Hi ikit-claw

Posted by vacho on August 25, 2017 at 1:30pm

Something like this but with Drupal 8 Entities. (Not query to db directly)

try {
$id = db_insert('example')
->fields(array(
'field1' => 'mystring',
))
->execute();
}
catch (Exception $e) {
$transaction->rollback();
watchdog_exception('my_type', $e);
}

The solution

Posted by vacho on August 25, 2017 at 10:51pm

I use this code solution:



$database = \Drupal::database();
$transaction = $database->startTransaction();
$id_branch = null;
try {
if(empty($id_branch)) {
throw new \Exception('Empty: Branch Entity id.');
}
$Branch = Entities::load($id_branch);
$branch_address = $Branch->getAddress();

for ($i = 0; $i < 8000; $i++) {
$values = array(
'entity' => $id_branch,
'name' => 'Store ' . $i,
'address' => $branch_address,
);
$Store = Store::create($values);
$Store->save();
}

}
catch (\Exception $e) {
$transaction->rollback();
watchdog_exception($e->getMessage(), $e);
throw new \Exception( $e->getMessage(), $e->getCode(), $e->getPrevious());
}

There is actually transactional support in Drupal

Posted by jaimeah on August 26, 2017 at 12:21am

I recently researched this info. It is part of the Drupal 7 (so I guess Drupal 8 also) API:

https://www.drupal.org/docs/7/api/database-api/transactions

AltStyle によって変換されたページ (->オリジナル) /