You are here

public function CivicrmEntityController::save in CiviCRM Entity 7

Same name and namespace in other branches
  1. 7.2 civicrm_entity_controller.inc \CivicrmEntityController::save()

Implements EntityAPIControllerInterface.

Parameters

$entity:

DatabaseTransaction $transaction: Optionally a DatabaseTransaction object to use. Allows overrides to pass in their transaction object.

Throws

Exception

Overrides EntityAPIController::save

File

./civicrm_entity_controller.inc, line 122

Class

CivicrmEntityController
Entity Controller for CiviCRM entities

Code

public function save($entity, DatabaseTransaction $transaction = NULL) {
  if (!civicrm_initialize()) {
    throw new Exception('civicrm inaccessible');
  }
  $params = (array) $entity;
  unset($params['is_new']);
  $params['version'] = 3;
  $params['sequential'] = 1;
  try {
    $entity->is_new = !empty($entity->is_new) || empty($entity->{$this->idKey});

    // @TODO should we call this hook when drupal saves (as opposed
    // to Civi?) ditto insert, update.
    $this
      ->invoke('presave', $entity);
    if ($entity->is_new) {
      $result = civicrm_api(substr($this->entityType, 8), 'create', $params);

      // $this->invoke('insert', $entity);
    }
    else {
      $result = civicrm_api(substr($this->entityType, 8), 'update', $params);

      // $this->invoke('update', $entity);
    }
    unset($entity->is_new);
    unset($entity->is_new_revision);
    unset($entity->original);
    if (!civicrm_error($result)) {
      return (object) $result['values'][0];
    }
    throw new Exception($result['error_message']);
  } catch (Exception $e) {
    watchdog_exception($this->entityType, $e);
    throw $e;
  }
}