You are here

autocomplete_limit.module in Autocomplete Limit Length 7

Functions for the autocomplete_limit module.

File

autocomplete_limit.module
View source
<?php

/**
 * @file
 * Functions for the autocomplete_limit module.
 */

/**
 * Implements hook_form_FORM_ID_alter().
 */
function autocomplete_limit_form_system_performance_settings_alter(&$form, $form_state) {
  $form['autocomplete_limit'] = array(
    '#type' => 'fieldset',
    '#title' => t('Autocomplete limit'),
    '#description' => t('Autocomplete textfields can cause SQL queries to be run whenever a user types a new character. Set a limit to avoid autocompleting short strings.'),
  );
  $form['autocomplete_limit']['autocomplete_limit'] = array(
    '#type' => 'textfield',
    '#title' => t('Limit'),
    '#description' => t('Enter the minimum length a string needs to be for autocomplete to run. Enter 0 to disable.'),
    '#size' => 2,
    '#maxlength' => 2,
    '#default_value' => variable_get('autocomplete_limit', 2),
    '#element_validate' => array(
      'autocomplete_limit_element_validate_integer_not_negative',
    ),
  );
}

/**
 * Validator for the limit.
 */
function autocomplete_limit_element_validate_integer_not_negative($element, &$form_state) {
  $value = $element['#value'];
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value < 0)) {
    form_error($element, t('%name must be a positive integer or 0.', array(
      '%name' => $element['#title'],
    )));
  }
}

/**
 * Implements hook_library_alter().
 *
 * Attach our own JS library whenever drupal.autocomplete is loaded.
 */
function autocomplete_limit_library_alter(&$libraries, $module) {
  $limit = variable_get('autocomplete_limit', 2);

  // Only inject our setting and js override if we've been configured.
  if (!empty($limit) && $module == 'system' && !empty($libraries['drupal.autocomplete'])) {
    drupal_add_js(array(
      'autocomplete_limit' => array(
        'limit' => $limit,
      ),
    ), 'setting');
    $library = drupal_get_path('module', 'autocomplete_limit') . '/js/autocomplete.limit.js';
    $libraries['drupal.autocomplete']['js'][$library] = array(
      'group' => JS_DEFAULT,
    );
  }
}