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
  • Did you try saving the bean first, add the address to to it and save the user bean again? Why aren't you using the default api's of the crm ? This should take care of alot of things ;)

Reply
  • Did you try saving the bean first, add the address to to it and save the user bean again? Why aren't you using the default api's of the crm ? This should take care of alot of things ;)

Children
  • Namely because I have the password already hashed with no way of knowing what the original password is. The default API expects cleartext password and also does not handle the email situation, only the User situation. Let me try your suggestion with the double save (I would be weird, as both the User and the EmailAddress saves correctly, only the link/relation does not)

  • I tried saving the user bean, calling the addAddress method and saving again, no luck