1. commerce
    1. 7
7 public DrupalCommerceEntityController::save($entity, DatabaseTransaction $transaction = NULL)

Permanently saves the given entity.

In case of failures, an exception is thrown.


$entity The entity to save.

$transaction An optional transaction object to pass thru. If passed the caller is responsible for rolling back the transaction if something goes wrong.

Return value

SAVED_NEW or SAVED_UPDATED depending on the operation performed.


includes/commerce.controller.inc, line 140

public function save($entity, DatabaseTransaction $transaction = NULL) {
  if (!isset($transaction)) {
    $transaction = db_transaction();
    $started_transaction = TRUE;

  try {
    // Load the stored entity, if any.
    if (!empty($entity->{$this->idKey}) && !isset($entity->original)) {
      // In order to properly work in case of name changes, load the original
      // entity using the id key if it is available.
      $entity->original = entity_load_unchanged($this->entityType, $entity->{$this->idKey});

    $this->invoke('presave', $entity);

    // When saving a new revision, unset any existing revision ID so as to
    // ensure that a new revision will actually be created, then store the old
    // revision ID in a separate property for use by hook implementations.
    if (!empty($this->revisionKey) && empty($entity->is_new) && !empty($entity->revision) && !empty($entity->{$this->revisionKey})) {
      $entity->old_revision_id = $entity->{$this->revisionKey};

    if (empty($entity->{$this->idKey}) || !empty($entity->is_new)) {
      // For new entities, create the row in the base table, then save the
      // revision.
      $op = 'insert';
      $return = drupal_write_record($this->entityInfo['base table'], $entity);
      if (!empty($this->revisionKey)) {
        drupal_write_record($this->entityInfo['revision table'], $entity);
        $update_base_table = TRUE;
    else {
      $op = 'update';
      $return = drupal_write_record($this->entityInfo['base table'], $entity, $this->idKey);

      if (!empty($this->revisionKey)) {
        if (!empty($entity->revision)) {
          drupal_write_record($this->entityInfo['revision table'], $entity);
          $update_base_table = TRUE;
        else {
          drupal_write_record($this->entityInfo['revision table'], $entity, $this->revisionKey);

    if (!empty($update_base_table)) {
      // Go back to the base table and update the pointer to the revision ID.
      db_update($this->entityInfo['base table'])
        ->fields(array($this->revisionKey => $entity->{$this->revisionKey}))
        ->condition($this->idKey, $entity->{$this->idKey})

    $this->invoke($op, $entity);

    // Ignore slave server temporarily.

    return $return;
  catch (Exception $e) {
    if (!empty($started_transaction)) {
      watchdog_exception($this->entityType, $e);
    throw $e;