In my module I'd like to allow admin/moderator to add some user specific settings e.g. user steve1 has to work between 8am and 3pm.

To make work easier for the admin I'd lke to use autocomplete field for choosing user.

Suggestions are made via user name, but to form, I need to pass uid instead of a name.

Is this possible via modyfinig my autocomplete code, or should I change provided name to uid during form_submit operation?

$matches = array();
$query = db_select('users', 'u');

$return = $query 
  ->fields('u', array(
  ->condition('u.name', '%' . db_like($string) . '%', 'LIKE')
  ->range(0, 10)

foreach ($return as $row) {
$matches[$row->name] = check_plain($row->name);

// return for JS

In your foreach you can add it

foreach ($return as $row) {
   $matches[$row->name . '[uid:' . $row->uid . ']'] = check_plain($row->name);

And in your submit handler you can find it with a simple preg_match like this one :

preg_match('/\[uid:(\d+)\]/', $form_state['values']['user_autocomplete'], $matches);
$uid = $matches[1];

Note that the $matches variable are not the same from the auto-complete part and the submit handler part.


http://drupal.org/node/1044286#comment-4062056 - that's much more complicated but also more flexible solution for passing more values with an autocomplete field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.