You are here

function sf_entity_save in Salesforce Suite 7

Same name and namespace in other branches
  1. 7.2 sf_entity/sf_entity.module \sf_entity_save()
2 calls to sf_entity_save()
sf_entity_entity_insert in sf_entity/sf_entity.module
sf_entity_entity_update in sf_entity/sf_entity.module

File

sf_entity/sf_entity.module, line 121
Integrates fieldable entities with the Salesforce API.

Code

function sf_entity_save($entity, $type, $op) {

  // When importing *from* Salesforce, don't export *back* to Salesforce.
  if (isset($entity->sf_entity_skip_export)) {
    return;
  }

  // If this is an update, and the node already has a salesforce mapping,
  // try to load it. If the load fails, we need to fetch the appropriate
  // fieldmap. Either way, we're upserting the salesforce record.
  $salesforce = array(
    'fieldmap' => NULL,
    'sfid' => NULL,
  );
  list($oid, $vid, $bundle) = entity_extract_ids($type, $entity);
  if ($oid) {
    $salesforce = salesforce_api_id_load($type, $bundle, $oid);
  }
  if (empty($salesforce['fieldmap'])) {
    $result = db_select('salesforce_field_map', 's')
      ->fields('s', array(
      'fieldmap',
    ))
      ->condition('drupal_entity', $type)
      ->condition('drupal_bundle', $bundle)
      ->condition('automatic', 1)
      ->execute();
    $map = $result
      ->fetch();
    if (!$map) {

      // If we didn't find a map, we're out of options. Bail out.
      return;
    }

    // Use the first fieldmap.
    $salesforce['fieldmap'] = $map->fieldmap;

    // Check if there is more than one fieldmap in the result.
    if (user_access('administer salesforce') && $result
      ->fetch()) {
      drupal_set_message(t('Warning: more than one "automatic" salesforce mapping detected. Used fieldmap @map.', array(
        '@map' => $map->fieldmap,
      )), 'error');
    }
  }

  // Finally, export the node to Salesforce.
  try {
    sf_entity_export($entity, $salesforce['fieldmap'], $salesforce['sfid']);
  } catch (Exception $e) {
    DrupalSalesforce::watchdog(SALESFORCE_LOG_SOME, 'Exception while attempting to export entity: ' . $e
      ->getMessage(), array(), WATCHDOG_ERROR, l('view', entity_uri($entity)));
  }
}