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?
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
Hi, Vacho, when you say error do you mean as entering the wrong information or system error?
Thanks
Hi ikit-claw
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
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
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