You are here

function synonyms_commerce_autocomplete_validate in Synonyms 7

Element validate for commerce product synonyms friendly autocomplete widget.

1 string reference to 'synonyms_commerce_autocomplete_validate'
synonyms_commerce_field_widget_form in synonyms_commerce/synonyms_commerce.module
Implements hook_field_widget_form().

File

synonyms_commerce/synonyms_commerce.module, line 198
Provides synonyms integration with Commerce.

Code

function synonyms_commerce_autocomplete_validate($element, &$form_state) {
  $input = drupal_map_assoc(drupal_explode_tags(drupal_strtolower($element['#value'])));
  $value = array();
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#entity_type'], $field['field_name'], $element['#bundle']);
  if (!empty($input)) {
    $target_bundles = synonyms_bundle_normalize('commerce_product', array_filter($instance['settings']['referenceable_types']));
    $efq = new EntityFieldQuery();
    $efq
      ->entityCondition('entity_type', 'commerce_product');
    $efq
      ->entityCondition('bundle', $target_bundles);
    $efq
      ->propertyCondition('title', $input, 'IN');
    $result = $efq
      ->execute();
    if (isset($result['commerce_product'])) {
      foreach (commerce_product_load_multiple(array_keys($result['commerce_product'])) as $product) {
        $label = drupal_strtolower(entity_label('commerce_product', $product));
        unset($input[$label]);
        $entity_id = entity_extract_ids('commerce_product', $product);
        $value[] = $entity_id[0];
      }
    }
    if (!empty($input)) {
      $behavior_implementations = synonyms_behavior_get('autocomplete', 'commerce_product', $target_bundles, TRUE);
      foreach ($behavior_implementations as $implementation) {
        $condition = db_and();
        $condition
          ->condition(AbstractSynonymsBehavior::COLUMN_SYNONYM_PLACEHOLDER, $input, 'IN');
        foreach ($implementation['object']
          ->synonymsFind($condition) as $synonym) {
          $value[] = $synonym->entity_id;
          unset($input[drupal_strtolower($synonym->synonym)]);
          if (empty($input)) {
            break 2;
          }
        }
      }
    }
  }
  $tmp = array_unique($value);
  $value = array();
  $column = array_keys($field['columns']);
  $column = reset($column);
  foreach ($tmp as $target_id) {
    $value[] = array(
      $column => $target_id,
    );
  }
  form_set_value($element, $value, $form_state);
}