开发者

How can I load user object by email address in Drupal 7?

开发者 https://www.devze.com 2023-04-02 08:03 出处:网络
Been searching furiously on Google and the Drupal docs for something equivalent tofunction user_load for D6 as开发者_运维百科 used here.

Been searching furiously on Google and the Drupal docs for something equivalent to function user_load for D6 as开发者_运维百科 used here.

The user_load function in D7 takes a UID while the D6 version is flexible enough to allow email addresses.

Any clues how I can achieve the same end in D7?

Thanks


... or you could just use user_load_by_mail: http://api.drupal.org/api/drupal/modules--user--user.module/function/user_load_by_mail/7


Got the answer on Drupal forums. Basically involves loading user Id associated with email directly from the database and then running user_load on success ...

function my_module_load_user_by_mail($mail){
 $query = db_select('user', 'u');
 $uid = $query->fields('u', array('uid'))->condition('u.uid', $mail)->execute()->fetchField();
  if($uid){
    return user_load($uid);
  }else{
    return FALSE;
  }
}

Module function is called instead and passed email ...

$user = my_module_load_by_mail($mail);


Just for background, user_load_from_mail()'s code relies on a $conditions parameter passed to user_load_multiple() that has been deprecated in 8.

Here's my stab at code that will probably be what's in user_load_from_mail() in future.

<?php
function load_user_by_email( $email )
{
    $query = new EntityFieldQuery();                                   
    $query->entityCondition('entity_type', 'user')                     
          ->propertyCondition('mail', $email);                         

    $result = $query->execute();                                       

    // not found?                                                      
    if (!isset($result['user'])) return;                               

    // found, keys are uids                                            
    $uids = array_keys($result['user']);                               
    $account = user_load($uids[0]);                                    
    return $account; 
}

Nb. There's theoretically no need to check for 2+ values returned since drupal insists emails are unique.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号