I need some advice
In our SF org we have enabled AccountContactRelation feature (which allows a contact to be linked to multiple accounts)
What i have found is, when "Contact 123" is moved from "Account A" to "Account B" (either manually via the contact page, or via Dataloader, ETL etc) it creates an AccountContactRelation record.
In the Scenario above the AccountContactRelation object would know look like this
ContactID | AccountID | Direct |
---|---|---|
Contact123 | Account A | False |
Contact123 | Account B | True |
What i would like to do is, any time a contact company changes then delete the previous record in the AccountContactRelation ( In this instance "Account A") .
Expected results
ContactID | AccountID | Direct |
---|---|---|
Contact123 | Account B | True |
The AccountContactRelation should only be created where a contact is linked to multiple accounts.
Best Answer
When you have the "Allow Contacts to be related to multiple Accounts" feature enabled, which is what gives you access to the
AccountContactRelation
object (ACR for short), every relationship to an Account becomes an ACR.The
Direct
flag is automatically managed by Salesforce, and it'strue
when the ACR's AccountId matches the Contact's AccountId. Further, Salesforce automatically creates an ACR record (if one doesn't already exist) when you set or change theAccountId
on Contact.A Contact without AccountId set is a private contact, and you won't be able to set indirect relationships on it until it gains a direct relationship (by setting AccountId on the Contact).
There is actually a setting you can tweak to accomplish what you're looking to do here.
Under Platform Tools in Lightning:
Feature Settings -> Sales -> Accounts -> Account Settings
You'll see When users replace the primary account on a contact record:
The default value is to "Save the relationship between the contact and the previous primary account as an indirect relationship"
but you can select "Delete the relationship between the contact and the previous primary account"
This setting appears to only be able to be viewed/edited through the web UI. It doesn't show up in the AccountSettings metadata (and there is no ContactSettings or AccountContactRelationSettings metadata).
Keep in mind that this only applies to ACRs that had Direct = true and change to Direct = false. Other indirect relationships should be unaffected.
But if you want to do this with code
Then you'll be able to detect the true -> false transition on the
IsDirect
field (that's the field's API name) on the ACR in an after update trigger.You'd need an after update trigger here to be able to then delete the record (unless you wanted to go async), and you'd need to create a new, in-memory instance of the record to be deleted (can't send the instance contained in
trigger.new
ortrigger.old
to adelete
dml call).