Deleting an email address from a contact using beans

Hello!

I want to delete a (primary) email address from a contact using beans - and I can’t figure out how.

I have a contact bean, retrieved using the id:

$person = BeanFactory::getBean("Contacts");
$person = $person->retrieve_by_string_fields(array('id' => $id));

I also have an email-address, $email. I know that $person has $email as primary email address, and I want to delete that email address (because it hard-bounced). I found something like removeAddress but it did not work. I think I need to do something with relationships but I can’t find anything about the emailAddress object that I can use. Any help is appreciated…

Regards,
Richard

Hi, welcome to the Community! :tada:

Yes, you need to load_relationship and then (from that relationship loaded) do a delete.

Look for examples online with the relationship name which I is email_addresses.

Like this one

Hi @pgr, thanx! This did the job:

Known: $id from Contact and $email to be deleted

$person = BeanFactory::getBean("Contacts");
$person = $person->retrieve_by_string_fields(array('id' => $id));
	
if ($person->load_relationship('email_addresses')) {
    			$relatedBeans = $person->get_linked_beans('email_addresses', 'email_address');
    			foreach ( $relatedBeans as $relatedBean ) {			
				if ($relatedBean->email_address == $email) {
					$person->email_addresses->delete($bean->id, $relatedBean->id);
				}
		         } 
}
1 Like

Instead of

$person = BeanFactory::getBean("Contacts");
$person = $person->retrieve_by_string_fields(array('id' => $id));

you can probably just use

$person = BeanFactory::getBean("Contacts", $id);
2 Likes