You are here

function webform_civicrm_save_custom in Webform CiviCRM Integration 7.2

Same name and namespace in other branches
  1. 6.2 webform_civicrm_utils.inc \webform_civicrm_save_custom()

Save custom data for an entity

1 call to webform_civicrm_save_custom()
webform_civicrm_process_submission in ./webform_civicrm_forms.inc
Webform submission handler Create/update CiviCRM contacts and related data Called by presave, insert and update webform hooks

File

./webform_civicrm_utils.inc, line 350
Webform CiviCRM module's common utility functions. The code in this file is cross-compatible with D6/Civi3 and D7/Civi4 Drupal-version-specific functions belong in webform_civicrm_dx_functions.inc

Code

function webform_civicrm_save_custom($entity, $entity_id, $entity_type = NULL) {
  $existing = webform_civicrm_get_custom($entity_id, $entity_type, FALSE);
  $params = array(
    'entityID' => $entity_id,
  );
  foreach ($entity as $table => $values) {
    if (substr($table, 0, 2) == 'cg' && is_array($values)) {
      if (empty($existing[$table])) {
        $existing[$table] = array();
      }
      $insert = 0;
      foreach ($values as $offset => $custom) {
        if ($id = each($existing[$table])) {
          $suf = $id['key'];
        }
        else {
          $suf = --$insert;
        }
        foreach ($custom as $k => $v) {
          $params[$k . '_' . $suf] = $v;
        }
      }
    }
  }
  if (count($params) > 1) {
    $result = CRM_Core_BAO_CustomValueTable::setValues($params);

    // Prevent wholesale failure by saving each param individually if there was an error while trying to save them all at once
    if (!empty($result['is_error'])) {
      $bt = debug_backtrace();
      array_shift($params);
      foreach ($params as $k => $v) {
        $single_param = array(
          'entityID' => $entity_id,
          $k => $v,
        );
        $result = CRM_Core_BAO_CustomValueTable::setValues($single_param);
        if (!empty($result['is_error'])) {
          watchdog('webform_civicrm', 'The CiviCRM "CustomValueTable::setValues" function returned the error: "%msg" when called by line !line of !file with the following parameters: "!params"', array(
            '%msg' => $result['error_message'],
            '!line' => $bt[0]['line'],
            '!file' => array_pop(explode('/', $bt[0]['file'])),
            '!params' => print_r($single_param, TRUE),
          ), WATCHDOG_ERROR);
        }
      }
    }
  }
}