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?

Comments

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?

Thanks

Hi ikit-claw

vacho's picture

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

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

jaimeah's picture

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

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