Opt out not working as expected

Hi all

I am trying to change the opt_out settings for a contact record
I have tried

$bean->email_address->opt_out = (bool) $opt_out;
$bean->email_address->save()
$bean->email_address->opt_out = (int) $opt_out;
$bean->email_address->save()
$bean->email_address->opt_out = (bool) $opt_out;
$bean->email_address->save($bean->id, $bean->module_name)
$bean->email_address->opt_out = (int) $opt_out;
$bean->email_address->save($bean->id, $bean->module_name)
$bean->email_opt_out = (bool) $opt_out;
$bean->save()
$bean->email_opt_out = (int) $opt_out;
$bean->save()

none of the above seem to change the opt_out settings on the record

I had a look for some clues in the SugarEmailAddress class and the closest thing I could find was addUpdateEmailAddress but this does not seem to be what I am looking for.

How does the CRM system do this normally?

Email addresses are related records, and the opt_out field is in email_addresses table.

I found this example online, it deletes all email addresses, which is not what you want, but it should be enough to get you going with the iteration of the email addresses linked to a Contact…

if ($bean->load_relationship('email_addresses')) {
    $relatedBeans = $bean->get_linked_beans('email_addresses', 'email_address');
    foreach ( $relatedBeans as $relatedBean ) {
           $bean->email_addresses->delete($bean->id, $relatedBean->id);
    } 
}

Your field is probably there at $bean->email_addresses->opt_out

Check the database, there are other fields there controlling confirmed opt_in, etc.

1 Like