From 97aec10c7f8ad9be0864dcab624c2c37499b92c6 Mon Sep 17 00:00:00 2001
Message-Id: <97aec10c7f8ad9be0864dcab624c2c37499b92c6.1339680266.git.dmitriy.trt@gmail.com>
From: "Dmitriy.trt" <dmitriy.trt@gmail.com>
Date: Thu, 14 Jun 2012 20:03:05 +0700
Subject: [PATCH] Port multiple improvements from D6

---
 js/views-autocomplete-filters-dependent.js         |   78 +++++++++
 views_autocomplete_filters.inc                     |  168 +++++++++++++-------
 views_autocomplete_filters.module                  |   48 +++---
 ..._autocomplete_filters_handler_filter_string.inc |  111 ++++++++++++-
 4 files changed, 319 insertions(+), 86 deletions(-)

diff --git a/js/views-autocomplete-filters-dependent.js b/js/views-autocomplete-filters-dependent.js
new file mode 100644
index 0000000..c2a194b
--- /dev/null
+++ b/js/views-autocomplete-filters-dependent.js
@@ -0,0 +1,78 @@
+(function ($) {
+
+/**
+ * Overrides function from misc/autocomplete.js to send full form values instead
+ * of just autocomplete value.
+ */
+Drupal.ACDB.prototype.search = function (searchString) {
+  var db = this;
+  this.searchString = searchString;
+
+  // See if this string needs to be searched for anyway.
+  searchString = searchString.replace(/^\s+|\s+$/, '');
+  if (searchString.length <= 0 ||
+    searchString.charAt(searchString.length - 1) == ',') {
+    return;
+  }
+
+  // See if this key has been searched for before.
+  if (this.cache[searchString]) {
+    return this.owner.found(this.cache[searchString]);
+  }
+
+  // Fill data with form values if we're working with dependent autocomplete
+  var data = '';
+  if (this.owner.isDependent()) {
+    data = this.owner.serializeOuterForm();
+  }
+
+  // Initiate delayed search.
+  if (this.timer) {
+    clearTimeout(this.timer);
+  }
+  this.timer = setTimeout(function () {
+    db.owner.setStatus('begin');
+
+    // Ajax GET request for autocompletion. We use Drupal.encodePath instead of
+    // encodeURIComponent to allow autocomplete search terms to contain slashes.
+    $.ajax({
+      type: 'GET',
+      url: db.uri + '/' + Drupal.encodePath(searchString),
+      data: data,
+      dataType: 'json',
+      success: function (matches) {
+        if (typeof matches.status == 'undefined' || matches.status != 0) {
+          db.cache[searchString] = matches;
+          // Verify if these are still the matches the user wants to see.
+          if (db.searchString == searchString) {
+            db.owner.found(matches);
+          }
+          db.owner.setStatus('found');
+        }
+      },
+      error: function (xmlhttp) {
+        alert(Drupal.ajaxError(xmlhttp, db.uri));
+      }
+    });
+  }, this.delay);
+};
+
+/**
+ * Function which checks if autocomplete depends on other filter fields.
+ */
+Drupal.jsAC.prototype.isDependent = function() {
+  return $(this.input).hasClass('views-ac-dependent-filter');
+};
+
+/**
+ * Returns serialized input values from form except autocomplete input.
+ */
+Drupal.jsAC.prototype.serializeOuterForm = function() {
+  return $(this.input)
+    .parents('form:first')
+    .find('select[name], textarea[name], input[name][type!=submit]')
+    .not(this.input)
+    .serialize();
+};
+
+})(jQuery);
\ No newline at end of file
diff --git a/views_autocomplete_filters.inc b/views_autocomplete_filters.inc
index c45d5f0..cef5804 100644
--- a/views_autocomplete_filters.inc
+++ b/views_autocomplete_filters.inc
@@ -1,79 +1,131 @@
 <?php
+
 /**
  * @file
  * Common functions for Autocomplete Filters module.
  */
+
 /**
- * Menu callback; Retrieve a pipe delimited string of autocomplete suggestions.
+ * Menu callback. Retrieves a pipe delimited string of autocomplete suggestions.
  */
-function views_autocomplete_filter($field_name = NULL, $view_name, $view_display, $string = '') {
-  static $autocomplete_filter_results;
-  $results_id = $field_name.'_'.$view_name.'_'.$view_display.'_'.$string;
-  if (isset($autocomplete_filter_results[$results_id])) {
-    drupal_json_output($autocomplete_filter_results[$results_id]);
-    return;
+function views_autocomplete_filter($filter_name, $view_name, $display_name, $string = '') {
+  if (trim($string) == '') {
+    // Ignore empty strings.
+    return drupal_json_output(array());
   }
-  $matches = array();
+
+  // Get the view and set current display. The view and display were checked by
+  // _views_autocomplete_filters_access_callback().
   $view = views_get_view($view_name);
-  if(!$view) {
-    $matches[''] = '<div class="reference-autocomplete">'. t('No matches were found for %string.', array('%string' => $string)) . '</div>';
-    drupal_json_output($autocomplete_filter_results[$results_id]);
-    return;
+  $view->set_display($display_name);
+
+  // Set display and display handler vars for quick access.
+  $display = $view->display[$display_name];
+  $display_handler = $display->handler;
+
+  // Get exposed filter options for our field.
+  // Also, check if filter is exposed and autocomplete is enabled for this filter
+  // (and if filter exists/exposed at all).
+  $filters = $display_handler->get_option('filters');
+  if (empty($filters[$filter_name]['exposed']) || empty($filters[$filter_name]['expose']['autocomplete_filter'])) {
+    return drupal_not_found();
+  }
+  $expose_options = $filters[$filter_name]['expose'];
+
+  // Determine field which will be used for output.
+  if (empty($expose_options['autocomplete_field'])) {
+    // Field is not set, report about it to watchdog and return empty array.
+    watchdog('views_autocomplete_filters', 'Field for autocomplete filter %label is not set in view %view, display %display', array(
+      '%label' => $expose_options['label'],
+      '%view' => $view->name,
+      '%display' => $display->id,
+    ), WATCHDOG_ERROR);
+    return drupal_json_output(array());
+  }
+  else {
+    $field_name = $expose_options['autocomplete_field'];
+  }
+
+  // Get field options and check field exists in this display.
+  $field_options = $view->get_item($display_name, 'field', $field_name);
+  if (empty($field_options)) {
+    // Field not exists, report about it to watchdog and return empty array.
+    watchdog('views_autocomplete_filters', 'Field for autocomplete filter %label not exists in view %view, display %display', array(
+      '%label' => $expose_options['label'],
+      '%view' => $view->name,
+      '%display' => $display->id,
+    ), WATCHDOG_ERROR);
+    return drupal_json_output(array());
+  }
+
+  // Overwrite the fields for the view with only one field we need.
+  $display_handler->set_option('fields', array($field_name => $field_options));
+  
+  // Collect exposed filter values and set them to the view.
+  if (!empty($expose_options['autocomplete_dependent'])) {
+    $exposed_input = $_GET;
+  }
+  else {
+    $exposed_input = array();
   }
-  $view->set_display($view_display);
-  // force to have no limit for results
-  $view->display_handler->set_option('items_per_page', 0);
-  $view->handler->items_per_page = $view->pager['items_per_page'] = 0;
-  $currentview = $view->display[$view_display];
-  // exposed form field name
-  if ($currentview->handler->options['defaults']['filters']) {
-    $currentview = $view->display['default'];
+  $exposed_input[$expose_options['identifier']] = $string;
+  $view->set_exposed_input($exposed_input);
+
+  // Disable cache for view, because caching autocomplete is a waste of time and memory.
+  $display_handler->set_option('cache', array('type' => 'none'));
+
+  // Force limit for results.
+  if (empty($expose_options['autocomplete_items'])) {
+    $pager = array(
+      'type' => 'full',
+    );
   }
   else {
-   $currentview = $view->display[$view_display];
+    $pager = array(
+      'type' => 'some',
+      'options' => array(
+        'items_per_page' => $expose_options['autocomplete_items'],
+        'offset' => 0,
+      ),
+    );
   }
-  $field_filter = $currentview->handler->options['filters'][$field_name];
-  $real_field_name = str_replace('_value', '', $field_name);
-  // assign string value to the exposed text filter
-  $view->exposed_input[$field_filter['expose']['identifier']] = $string;
-
-  $item = $view->get_item($view_display, 'filter', $field_name);
-  // overwrite the fields for the view
-  $view->display[$view_display]->handler->options['fields'] = array($real_field_name => $view->display[$view_display]->handler->options['fields'][$real_field_name]);
-  $view->display[$view_display]->display_options['fields'] = array($real_field_name => $view->display[$view_display]->handler->options['fields'][$real_field_name]);
+  $display_handler->set_option('pager', $pager);
+
+  // Execute view query.
+  $view->pre_execute();
   $view->execute($view->current_display);
- 
-  $currentview = $view->display[$view_display];
-  // views field handler data
-  $field = $currentview->handler->handlers['field'][$real_field_name];
+  $view->post_execute();
+
+  // Render field on each row and fill matches array.
+  $use_raw_suggestion = !empty($expose_options['autocomplete_raw_suggestion']);
+  $use_raw_dropdown = !empty($expose_options['autocomplete_raw_dropdown']);
+  $field = $view->field[$field_name];
   $field_alias = $field->field_alias;
-  // check if it's a field
-  if(0 === strpos($field->table,'field_data')){
-    $field_alias_name = 'field_'.$field->field;
-    foreach ($view->result as $id => $row) {
-    // Add a class wrapper for a few required CSS overrides.
-      if (!empty($row->$field_alias)) {
-        $x = $row->$field_alias_name;
-        $matches[$x[0]['rendered']['#markup']] = '<div class="reference-autocomplete">'. $x[0]['raw']['safe_value'] .'</div>';
-      }
+  
+  $matches = array();
+  $view->row_index = 0;
+  foreach ($view->result as $count => $row) {
+    $view->row_index = $count;
+    $rendered_field = $raw_field = '';
+
+    // Render field only if suggestion or dropdown item not in RAW format.
+    if (!$use_raw_suggestion || !$use_raw_dropdown) {
+      $rendered_field = $field->theme($row);
     }
-  }
-  else {
-    foreach ($view->result as $id => $row) {
+    
+    $dropdown = $use_raw_dropdown ? check_plain($row->{$field_alias}) : $rendered_field;
+    if ($dropdown != '') {
+      $suggestion = $use_raw_suggestion ? $row->{$field_alias} : decode_entities($rendered_field);
+
       // Add a class wrapper for a few required CSS overrides.
-      if (!empty($row->$field_alias)) {
-        $matches[$row->$field_alias] = '<div class="reference-autocomplete">'. $row->$field_alias .'</div>';
-      }
+      $matches[$suggestion] = '<div class="reference-autocomplete">' . $dropdown . '</div>';
     }
   }
-  if (!empty($matches)) {
-    $autocomplete_filter_results[$results_id] = $matches;
-  }
-  elseif (!empty($view->result)) {
-    $matches[''] = '<div class="reference-autocomplete">'. t('The %field is required but is missing or excluded from display.', array('%field' => $field_filter['expose']['label'])) . '</div>';
-  }
-  else {
-    $matches[''] = '<div class="reference-autocomplete">'. t('No matches were found for %string.', array('%string' => $string)) . '</div>';
+  unset($view->row_index);
+
+  if (empty($matches)) {
+    $matches[''] = '<div class="reference-autocomplete">' . t('The %string return no results. Please try something else.', array('%string' => $string)) . '</div>';
   }
+
   drupal_json_output($matches);
-}
\ No newline at end of file
+}
diff --git a/views_autocomplete_filters.module b/views_autocomplete_filters.module
index d7ff1ad..b1f91f4 100644
--- a/views_autocomplete_filters.module
+++ b/views_autocomplete_filters.module
@@ -1,13 +1,16 @@
 <?php
+
 /**
- * Implementation of hook_menu().
+ * Implements hook_menu().
  */
 function views_autocomplete_filters_menu() {
   $items = array();
-  $items['autocomplete_filter'] = array(
+  $items['autocomplete_filter/%/%/%'] = array(
     'title' => 'Autocomplete Filters',
     'page callback' => 'views_autocomplete_filter',
-    'access arguments' => array('access content'),
+    'page arguments' => array(1, 2, 3),
+    'access callback' => '_views_autocomplete_filters_access_callback',
+    'access arguments' => array(2, 3),
     'file' => 'views_autocomplete_filters.inc',
     'type' => MENU_CALLBACK,
   );
@@ -15,27 +18,30 @@ function views_autocomplete_filters_menu() {
 }
 
 /**
- * Implementation of hook_views_api().
+ * Access callback of autocomplete menu item.
+ *
+ * @param string $view_name
+ * @param string $display_name
+ *
+ * @return bool
+ */
+function _views_autocomplete_filters_access_callback($view_name, $display_name) {
+  $view = views_get_view($view_name);
+
+  if (empty($view) || !$view->set_display($display_name)) {
+    // No such view or something is wrong with display
+    // (no such display, broken handler, etc.)
+    return FALSE;
+  }
+
+  return $view->access(array($display_name));
+}
+
+/**
+ * Implements hook_views_api().
  */
 function views_autocomplete_filters_views_api() {
   return array(
     'api' => 3.0,
   );
 }
-
-/**
- * Implementation of hook_form_FORMID_alter() for views_exposed_form.
- */
-function views_autocomplete_filters_form_views_exposed_form_alter(&$form, $form_state) {
-  // Go through each filter checking for a 'autocomplete' setting
-  foreach ($form_state['view']->filter as $field => $filter) {
-    if ($filter->options['exposed']) {
-      // If using selective filters, filter the value_options based on view results
-      if (isset($filter->options['expose']['autocomplete_filter']) && !empty($filter->options['expose']['autocomplete_filter'])) {
-        $field_id = $form['#info']["filter-$field"]['value'];
-        unset($form[$field_id]['#default_value']);
-        $form[$field_id]['#autocomplete_path'] = 'autocomplete_filter/'.$field.'/'.$form_state['view']->name.'/'.$form_state['view']->current_display;
-      }
-    }
-  }
-}
\ No newline at end of file
diff --git a/views_autocomplete_filters_handler_filter_string.inc b/views_autocomplete_filters_handler_filter_string.inc
index 7ebcdbd..170704a 100644
--- a/views_autocomplete_filters_handler_filter_string.inc
+++ b/views_autocomplete_filters_handler_filter_string.inc
@@ -11,18 +11,115 @@ class views_autocomplete_filters_handler_filter_string extends views_handler_fil
   function option_definition() {
     $options = parent::option_definition();
 
-    $options['expose']['contains']['autocomplete_filter'] = array('default' => 0);
+    $options['expose']['contains'] += array(
+      'autocomplete_filter' => array('default' => 0),
+      'autocomplete_items' => array('default' => 10),
+      'autocomplete_field' => array('default' => ''),
+      'autocomplete_raw_suggestion' => array('default' => TRUE),
+      'autocomplete_raw_dropdown' => array('default' => TRUE),
+      'autocomplete_dependent' => array('default' => FALSE),
+    );
 
     return $options;
   }
 
   function expose_form(&$form, &$form_state) {
     parent::expose_form($form, $form_state);
-    $form['expose']['autocomplete_filter'] = array(
-      '#type' => 'checkbox',
-      '#title' => t('Use Autocomplete'),
-      '#default_value' => !empty($this->options['expose']['autocomplete_filter']),
-      '#description' => t('Use Autocomplete for this filter.'),
+
+    $field_options = $this->view->display_handler->get_field_labels();
+    if (empty($field_options)) {
+      $field_options[''] = t('<Add some fields to view>');
+    }
+
+    // Build form elements for the right side of the exposed filter form
+    $form['expose'] += array(
+      'autocomplete_filter' => array(
+        '#type' => 'checkbox',
+        '#title' => t('Use Autocomplete'),
+        '#default_value' => $this->options['expose']['autocomplete_filter'],
+        '#description' => t('Use Autocomplete for this filter.'),
+      ),
+      'autocomplete_items' => array(
+        '#type' => 'textfield',
+        '#title' => t('Maximum number of items in Autocomplete'),
+        '#default_value' => $this->options['expose']['autocomplete_items'],
+        '#description' => t('Enter 0 for no limit.'),
+        '#dependency' => array('edit-options-expose-autocomplete-filter' => array(TRUE)),
+      ),
+      'autocomplete_dependent' => array(
+        '#type' => 'checkbox',
+        '#title' => t('Suggestions depend on other filter fields'),
+        '#default_value' => $this->options['expose']['autocomplete_dependent'],
+        '#description' => t('Autocomplete suggestions will be filtered by other filter fields'),
+        '#dependency' => array('edit-options-expose-autocomplete-filter' => array(TRUE)),
+      ),
+      'autocomplete_field' => array(
+        '#type' => 'select',
+        '#title' => t('Field with autocomplete results'),
+        '#default_value' => $this->options['expose']['autocomplete_field'],
+        '#options' => $field_options,
+        '#description' => t('Selected field will be used for dropdown results of autocomplete. In most cases it should be the same field you use for filter.'),
+        '#dependency' => array('edit-options-expose-autocomplete-filter' => array(TRUE)),
+      ),
+      'autocomplete_raw_dropdown' => array(
+        '#type' => 'checkbox',
+        '#title' => t('Unformatted dropdown'),
+        '#default_value' => $this->options['expose']['autocomplete_raw_dropdown'],
+        '#description' => t('Use unformatted data from database for dropdown list instead of field formatter result. Value will be printed as plain text.'),
+        '#dependency' => array('edit-options-expose-autocomplete-filter' => array(TRUE)),
+      ),
+      'autocomplete_raw_suggestion' => array(
+        '#type' => 'checkbox',
+        '#title' => t('Unformatted suggestion'),
+        '#default_value' => $this->options['expose']['autocomplete_raw_suggestion'],
+        '#description' => t('The same as above, but for suggestion (text appearing inside textfield when item is selected).'),
+        '#dependency' => array('edit-options-expose-autocomplete-filter' => array(TRUE)),
+      ),
     );
   }
-}
\ No newline at end of file
+
+  public function value_form(&$form, &$form_state) {
+    parent::value_form($form, $form_state);
+
+    if (empty($form_state['exposed']) || empty($this->options['expose']['autocomplete_filter'])) {
+      // It's not an exposed form or autocomplete is not enabled.
+      return;
+    }
+    
+    if (empty($form['value']['#type']) || $form['value']['#type'] !== 'textfield') {
+      // Not a textfield.
+      return;
+    }
+    
+    // Add autocomplete path to the exposed textfield.
+    $form['value']['#autocomplete_path'] = 'autocomplete_filter/' . $this->field . '/' . $this->view->name . '/' . $this->view->current_display;
+    
+    // Add JS script with core autocomplete overrides to the end of JS files
+    // list to be sure it is added after the "misc/autocomplete.js" file. Also
+    // mark the field with special class.
+    if (!empty($this->options['expose']['autocomplete_dependent'])) {
+      $file_path = drupal_get_path('module', 'views_autocomplete_filters') . '/js/views-autocomplete-filters-dependent.js';
+      drupal_add_js($file_path, array(
+        'weight' => 99,
+      ));
+
+      $form['value']['#attributes']['class'][] = 'views-ac-dependent-filter';
+    }
+  }
+
+  public function validate() {
+    $errors = parent::validate();
+
+    if (!empty($this->options['exposed']) && !empty($this->options['expose']['autocomplete_filter'])) {
+      $fields = $this->view->display_handler->get_handlers('field');
+      $field_name = $this->options['expose']['autocomplete_field'];
+      if (empty($field_name) || empty($fields[$field_name])) {
+        $errors[] = t('Field with autocomplete results is not selected for %label filter.', array(
+          '%label' => $this->ui_name(TRUE),
+        ));
+      }
+    }
+
+    return $errors;
+  }
+}
-- 
1.7.10

