Skip to content

Instantly share code, notes, and snippets.

@benclark
Created January 21, 2013 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benclark/4590024 to your computer and use it in GitHub Desktop.
Save benclark/4590024 to your computer and use it in GitHub Desktop.
Example of how to add an autocomplete path to a textfield and convert it to the user ID before saving it to a variable via `system_settings_form()`.
<?php
/**
* @file
* Example of how to add an autocomplete path to a textfield and convert it to
* the user ID before saving it to a variable via `system_settings_form()`.
*/
/**
* Admin settings form.
*/
function D6MODULE_admin_settings_form() {
$form = array();
$form['D6MODULE_user_autocomplete'] = array(
'#type' => 'textfield',
// Drupal core already provides an autocomplete path for users.
'#autocomplete_path' => 'user/autocomplete',
'#value_callback' => 'D6MODULE_admin_user_autocomplete_value_callback',
'#element_validate' => array('D6MODULE_admin_user_autocomplete_validate'),
);
return system_settings_form($form);
}
/**
* Value callback for the `D6MODULE_user_autocomplete` field.
*/
function D6MODULE_admin_user_autocomplete_value_callback($element, $edit = FALSE) {
if (func_num_args() == 1) {
// No value yet, so use #default_value if available.
if (isset($element['#default_value']) && is_numeric($element['#default_value'])) {
// Convert to autocomplete value.
$account = user_load(array('uid' => $element['#default_value']));
return isset($account->name) ? $account->name : '';
}
return '';
}
return $edit;
}
/**
* Element validate callback for the `D6MODULE_user_autocomplete` field.
*/
function D6MODULE_admin_user_autocomplete_validate($element, &$form_state) {
if (!empty($element['#value'])) {
// Check that the value is a valid user.
$uid = db_result(db_query("SELECT uid FROM {users} WHERE name = '%s'", $element['#value']));
if (!isset($uid) || empty($uid)) {
form_error($element, t('User must be a valid user.'));
}
else {
// If no error, set the value on the element to the validated uid.
form_set_value($element, $uid, $form_state);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment