Contact $bean->save() deletes related email address

HI all,

I have an unexpected behaviour:

I have an API Entry Point, where a contact and its email address is saved at the database. Below some simplified source code:

Fullscreen
1
2
3
4
5
6
7
8
$bean = BeanFactory::newBean("Contacts");
$bean->last_name = $last_name;
$bean->status = "New";
$bean->save();
$sea = new SugarEmailAddress();
$sea->addAddress($email, true, false, false, false);
$sea->save($bean->id, "Contacts");
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Then some logic is done and in some cases the contact need to be adjusted after that, so the contact is loaded with getBean and saved:

Fullscreen
1
2
3
4
5
$bean_id = 'TheIDoftheSavedContactFromAbove!';
$bean2 = BeanFactory::getBean("Contacts", $bean_id);
$bean2->a_example_field = "Test entry";
$bean2->save();
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

After that $bean2->save(), the relation of the Contact to the Email address is marked as deleted=1

How to stop this strange behaviour.

Many thanks

Best Regards

Sven

  • Hi Sven,

    In your code, you had added an email via SugarEmailAddress, but the Contact $bean doesn't know about the relationship yet.

    When you do BeanFactory::getBean in the next few lines, you get a cached version of the previously created $bean, and it deletes the relationship on save, because it overwrites the relationship based on cached version.

    To fix it, you have to retrieve it without cache, to refresh the email, like:

    $bean2 = BeanFactory::getBean("Contacts", $bean_id, ['use_cache' => false]);

    OR
    $bean2 = new Contact();
    $bean2->retrieve($bean_id);
  • Thank you very much, this solved my issue. Slight smile