Hi, Is there any core function to get uid from username in Drupal? Or I should perform a db query? my field is a textfield with '#autocomplete_path' equal to 'user/autocomplete'
+4
A:
You can use the user_load
function. See http://api.drupal.org/api/function/user_load/6
In particular see http://api.drupal.org/api/function/user_load/6#comment-6439
So you would do something like this:
// $name is the user name
$account = user_load(array('name' => check_plain($name)));
// uid is now available as $account->uid
Sid NoParrots
2010-10-05 06:36:51
To get the uid, this is quite a slow way to do it, as it involves all modules that implement hook_user creating an unknown amount of queries.
googletorp
2010-10-05 06:39:52
@googletorp: Agree this is slow. But I thought it would be simpler for Hamid this way. Practically speaking `node_load`, which is similar in concept to `user_load` happens a lot in Drupal, if I'm not wrong, and yet doesn't adversely affect performance in most cases. So I thought it would be a good idea to recommend `user_load`
Sid NoParrots
2010-10-05 06:56:02
@NoParrots: When he himself asks if he should just do a db query, I'm sure he will be able to do it. It's not that complicated after all.
googletorp
2010-10-05 07:05:39
+1 - this would be the correct API function to use. Concerning performance, `user_load()` does not use static caching like `node_load()` does, so if that call is going to be made often during a page cycle, it _might_ be better to do a custom query.
Henrik Opel
2010-10-05 09:07:46
A:
There is no ready made API function for this, not that I know of. But you can make your own if you needs several places. It should be pretty simple and straight forward to query the db for the uid.
googletorp
2010-10-05 06:37:06