How to add email address to User programatically?

Hello. I am writing a custom REST API to push users from another product of ours into CRM (on premise, not sugar cloud). The code that handles saving or editing the user is the following:

private function processUserBean($user_bean,string $user_name,string $user_hash,string $first_name,string $last_name,string $title,string $email,int $is_admin,string $status):void
{
 $user_bean->user_name=$user_name;
 $user_bean->first_name=$first_name;
 $user_bean->last_name=$last_name;
 $user_bean->title=$title;
 $user_bean->status=$status;
 $user_bean->is_admin=$is_admin;
 $user_bean->user_hash=$user_hash;
 if (!empty($email))
 {
  $user_bean->emailAddress->addAddress($email);
 }
 $user_bean->save();
}

Every forum and documentation directs me to this ->emailAddress->addAddress approach. This ALMOST works. What happens is the following: The User is created correctly in the database (record in users table), the email address is created correctly (record in email_addresses table) BUT the link between them, a record in email_addr_bean_rel table is NOT CREATED. What am I doing wrong?

Parents Reply
  • ,

    Did you follow all the instructions in the link  posted? I think you may be re-saving the User bean when what you need to do is explicitly save the email address link bean. I think your code needs to be something like:

    ... //all the rest of your code;
    
    $user_bean->save();
    
    if (!empty($email))
    {
      $user_bean->emailAddress->addAddress($email);
      $user_bean->emailAddress->save($user_bean->id, $user_bean->module_dir);
    }

    If you want it to be the Primary address then simply use: addAddress($email, true) instead.

    That should properly save the linked email address to the User record.

    Thanks,

    JH.

Children