You are here

function webform_autocomplete_js in Webform Autocomplete 7

Same name and namespace in other branches
  1. 7.2 autocomplete.inc \webform_autocomplete_js()

Autocomplete callback.

1 string reference to 'webform_autocomplete_js'
webform_autocomplete_menu in ./webform_autocomplete.module
Implements hook_menu().

File

./autocomplete.inc, line 236
Autocomplete component.

Code

function webform_autocomplete_js($node, $cid, $str = '') {
  if ($str !== '') {
    $component = $node->webform['components'][$cid];
    $result_count = (int) $component['extra']['autocomplete_result_count'];
    $match_rule = $component['extra']['autocomplete_match_rule'];
    $results = array();
    $count = 0;

    // Search from prepulated options
    if (!empty($component['extra']['autocomplete_items'])) {
      $options = preg_split('/\\r\\n|\\r|\\n/', $component['extra']['autocomplete_items']);
      foreach ($options as $val) {
        $is_match = FALSE;
        if ($match_rule == 0) {
          if (strpos($val, $str, 0) === 0) {
            $is_match = TRUE;
          }
        }
        elseif ($match_rule == 1) {
          if (stripos($val, $str) !== FALSE) {
            $is_match = TRUE;
          }
        }
        else {
          if (strpos($val, $str) + strlen($str) == strlen(trim($val))) {
            $is_match = TRUE;
          }
        }
        if ($is_match) {
          $results[$val] = $val;

          // Limit to 20 results
          if (++$count >= $result_count) {
            break;
          }
        }
      }
    }

    // Search from existing submissions
    // Only fire the query if we have fewer than $result_count results already
    if (!empty($component['extra']['autocomplete_existing']) && $count < $result_count) {
      $str_like = db_like($str);
      if ($match_rule == 1 || $match_rule == 2) {
        $str_like = '%' . $str_like;
      }
      if ($match_rule == 0 || $match_rule == 1) {
        $str_like = $str_like . '%';
      }
      $db = db_query("SELECT DISTINCT data\n        FROM {webform_submitted_data}\n        WHERE nid = :nid AND cid = :cid AND data LIKE :str LIMIT " . ($result_count - $count), array(
        ':nid' => $node->nid,
        ':cid' => $cid,
        ':str' => $str_like,
      ));
      foreach ($db as $row) {
        $results[$row->data] = $row->data;
      }
    }

    // Sort php and sql results together
    natcasesort($results);
    drupal_json_output($results);
  }
  exit;
}