Hi I am using an ajax autocomplete textbox to return a username, at the moment I am using the default function user/autocomplete to do this.

this returns the username fine of the user I am looking for but is it possible to also return the uid doing an ajax call in this way as a hidden variable or not, and if not what is the correct way of doing so.

Thanks

Comments

jaypan’s picture

No, you can't return it as a hidden value. You basically have two options:

1) In your custom autocomplete callback, you set the UID in the key. Ex:

$matches['[' . $result->uid . '] ' . $result->name] = $result->name;

This will display the username only to users when they are typing, but when they click on a name, the value entered in the textfield will be prefixed with the UID like this:
[123] Dave
You can then retrieve the UID in your submit function like this:

preg_match('/^\[(\d+)\]/', $form_state['values']['account'], $matches);
if(isset($matches[1]))
{
  $uid = $matches[1];
}

2) Leave the autocomplete only showing the usernames:

$matches[$result->username] = $result->username;

This will enter only the username when the user selects a user. Since usernames are unique by default, you can then get the user ID like this in your submit function:

$account = user_load_by_name($form_state['values']['account']);
$uid = $account->uid;

Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
gibbo1715’s picture

That's fantastic, thanks yet again for your assistance

gibbo1715’s picture

Sorry posted in error