You are here

function synonyms_autocomplete_entity_validate in Synonyms 7

Form element validate handler.

Validate entity reference synonyms friendly autocomplete element.

1 string reference to 'synonyms_autocomplete_entity_validate'
synonyms_field_widget_form in ./synonyms.module
Implements hook_field_widget_form().

File

./synonyms.module, line 480
Provide synonyms feature for Drupal entities.

Code

function synonyms_autocomplete_entity_validate($element, &$form_state) {
  $input = drupal_map_assoc(drupal_explode_tags(drupal_strtolower($element['#value'])));
  $value = array();
  if (!empty($input)) {
    $field = field_info_field($element['#field_name']);
    $instance = field_info_instance($element['#entity_type'], $field['field_name'], $element['#bundle']);
    $handler = entityreference_get_selection_handler($field, $instance);
    foreach ($input as $k => $v) {
      $matches = $handler
        ->getReferencableEntities($v, '=');
      foreach ($matches as $bundle => $entity_ids) {
        $entities = entity_load($field['settings']['target_type'], array_keys($entity_ids));
        foreach ($entity_ids as $entity_id => $label) {
          $value[] = $entity_id;
          unset($input[drupal_strtolower(entity_label($field['settings']['target_type'], $entities[$entity_id]))]);
        }
      }
    }
    if (!empty($input)) {
      $behavior_implementations = synonyms_behavior_get('autocomplete', $field['settings']['target_type'], synonyms_field_target_bundles($field), TRUE);
      foreach ($behavior_implementations as $implementation) {
        $condition = db_and();
        $condition
          ->condition(AbstractSynonymsBehavior::COLUMN_SYNONYM_PLACEHOLDER, $input, 'IN');
        foreach ($implementation['object']
          ->synonymsFind(clone $condition) as $synonym) {
          $value[] = $synonym->entity_id;
          unset($input[drupal_strtolower($synonym->synonym)]);
          if (empty($input)) {
            break 2;
          }
        }
      }
    }
  }
  $tmp = array_unique($value);
  $value = array();
  foreach ($tmp as $target_id) {
    $value[] = array(
      'target_id' => $target_id,
    );
  }
  form_set_value($element, $value, $form_state);
}