Drupal 8 Transaction with entities

vacho's picture

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?


Hi, Vacho, when you say error

ikit-claw's picture

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


Hi ikit-claw

vacho's picture

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

try {
$id = db_insert('example')
'field1' => 'mystring',
catch (Exception $e) {
watchdog_exception('my_type', $e);

The solution

vacho's picture

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);

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

There is actually transactional support in Drupal

jaimeah's picture

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


Drupal Dojo

Group organizers

Group events

Add to calendar

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds:

Hot content this week