You are here

public function SearchApiAutocompleteSearch::alterElement in Search API Autocomplete 7

Helper method for altering a textfield form element to use autocompletion.

File

./search_api_autocomplete.entity.php, line 177
Contains SearchApiAutocompleteSearch.

Class

SearchApiAutocompleteSearch
Describes the autocomplete settings for a certain search.

Code

public function alterElement(array &$element, array $fields = array()) {
  if (search_api_autocomplete_access($this)) {

    // Add option defaults (in case of updates from earlier versions).
    $options = $this->options + array(
      'submit_button_selector' => ':submit',
      'autosubmit' => TRUE,
      'min_length' => 1,
    );
    $fields_string = $fields ? implode(' ', $fields) : '-';
    $module_path = drupal_get_path('module', 'search_api_autocomplete');
    $autocomplete_path = 'search_api_autocomplete/' . $this->machine_name . '/' . $fields_string;
    $js_settings = array();
    if ($options['submit_button_selector'] != ':submit') {
      $js_settings['selector'] = $options['submit_button_selector'];
    }
    if (($delay = variable_get('search_api_autocomplete_delay')) !== NULL) {
      $js_settings['delay'] = $delay;
    }

    // Allow overriding of the default handler with a custom script.
    $path_overrides = variable_get('search_api_autocomplete_scripts', array());
    if (!empty($path_overrides[$this->machine_name])) {
      $autocomplete_path = NULL;
      $override = $path_overrides[$this->machine_name];
      if (is_scalar($override)) {
        $autocomplete_path = url($override, array(
          'absolute' => TRUE,
          'query' => array(
            'machine_name' => $this->machine_name,
          ),
        ));
      }
      elseif (!empty($override['#callback']) && is_callable($override['#callback'])) {
        $autocomplete_path = call_user_func($override['#callback'], $this, $element, $override);
      }
      if (!$autocomplete_path) {
        return;
      }
      $js_settings['custom_path'] = TRUE;
    }
    $element['#attached']['css'][] = $module_path . '/search_api_autocomplete.css';
    $element['#attached']['js'][] = $module_path . '/search_api_autocomplete.js';
    if ($js_settings) {
      $element['#attached']['js'][] = array(
        'type' => 'setting',
        'data' => array(
          'search_api_autocomplete' => array(
            $this->machine_name => $js_settings,
          ),
        ),
      );
    }
    $element['#autocomplete_path'] = $autocomplete_path;
    $element += array(
      '#attributes' => array(),
    );
    $element['#attributes'] += array(
      'class' => array(),
    );
    if ($options['autosubmit']) {
      $element['#attributes']['class'][] = 'auto_submit';
    }
    $element['#attributes']['data-search-api-autocomplete-search'] = $this->machine_name;
    if ($options['min_length'] > 1) {
      $element['#attributes']['data-min-autocomplete-length'] = $options['min_length'];
    }
  }
}