/**
* removes the address relation from a contact and also deletes the address if it has no more relations.
*
* @param Contact $contact
* @param ContactAddress $contactAddress
*
* @return mixed|void
*
* @throws \Exception
*/
public function removeAddressRelation($contact, $contactAddress)
{
if (!$contact || !$contactAddress) {
throw new \Exception('Contact and ContactAddress cannot be null');
}
// reload address to get all data (including relational data)
/** @var Address $address */
$address = $contactAddress->getAddress();
$address = $this->em->getRepository('SuluContactBundle:Address')->findById($address->getId());
$isMain = $contactAddress->getMain();
// remove relation
$contact->removeContactAddress($contactAddress);
$address->removeContactAddress($contactAddress);
// if was main, set a new one
if ($isMain) {
$this->setMainForCollection($contact->getContactAddresses());
}
// delete address if it has no more relations
if (!$address->hasRelations()) {
$this->em->remove($address);
}
$this->em->remove($contactAddress);
}