You are here

function salesforce_mapping_object_form_validate in Salesforce Suite 7.3

Implements hook_form_validate().

File

modules/salesforce_mapping/includes/salesforce_mapping_object.admin.inc, line 61

Code

function salesforce_mapping_object_form_validate($form, &$form_state) {
  $values =& $form_state['values'];
  $mapping_object = $form_state['salesforce_mapping_object'];
  $entity_type = isset($values['entity_type']) ? $values['entity_type'] : $mapping_object->entity_type;
  $entity_id = isset($values['entity_id']) ? $values['entity_id'] : $mapping_object->entity_id;
  $entity = entity_load_single($entity_type, $entity_id);
  if (!$entity) {

    // Invalid entity.
    form_set_error('entity_id', t('Entity is invalid.'));
    return;
  }
  else {
    list($entity_id, , $bundle) = entity_extract_ids($entity_type, $entity);
    $mappings = salesforce_mapping_load_multiple(array(
      'drupal_entity_type' => $entity_type,
      'drupal_bundle' => $bundle,
    ));

    // Check that entity is of a mapped type/bundle.
    if (empty($mappings)) {
      form_set_error('entity_id', t('Selected entity is of a bundle that is not mapped.'));
      return;
    }
  }

  // For new mappings, validate entity type/id.
  if (!empty($mapping_object->is_new) && $mapping_object->is_new) {

    // Check for existing mapping based on the Drupal entity.
    $mapping_object_drupal = salesforce_mapping_object_load_by_drupal($entity_type, $entity_id, TRUE);
    if ($mapping_object_drupal && (empty($mapping_object->salesforce_mapping_object_id) || $mapping_object_drupal->salesforce_mapping_object_id != $mapping_object->salesforce_mapping_object_id)) {
      form_set_error('entity_id', t('Drupal entity is already mapped to a Salesforce object.'));
    }
  }
  $mapping = reset($mappings);

  // Convert to 18-char if 15-char ID was given.
  $values['salesforce_id'] = Salesforce::convertId($values['salesforce_id']);

  // Check for existing mapping based on the Salesforce Id.
  $mapping_object_sf = salesforce_mapping_object_load_by_sfid($values['salesforce_id'], TRUE);
  $sf_object_type = $mapping->salesforce_object_type;
  if ($mapping_object_sf && (empty($mapping_object->salesforce_mapping_object_id) || $mapping_object_sf->salesforce_mapping_object_id != $mapping_object->salesforce_mapping_object_id)) {
    form_set_error('salesforce_id', t('Salesforce object is already mapped to a Drupal entity.'));
  }
  $sfapi = salesforce_get_api();

  // Not authorized, we need to bail this time around.
  if (!$sfapi
    ->isAuthorized()) {
    form_set_error('salesforce_id', t('Salesforce is not authorized.'));
  }
}