function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mike SummittMike Summitt 

How to prevent accountcontactrole, casecontactrole from cross linking.

We have a business rule that contact roles on an account or a case must be contacts that actually belong to that account, not cross linked from some other account.  So I wrote a trigger....
trigger EditAccountContactRoleSameAccount on AccountContactRole (before insert, before update)
{
    TriggerControl__c thisTrigger = Utilities.GetTriggerControl('EditAccountContactRoleSameAccount', false, false, false);
    if (thisTrigger.Enabled__c) {
        Set<Id> theContacts = new Set<Id>();
        for (AccountContactRole acr : Trigger.new) {
        if (!theContacts.contains(acr.ContactID)) {
            theContacts.add(acr.ContactID);
        }
        Map<Id, AccountContactRole> ContactsAccounts = new Map<Id, AccountContactRole>()
        for (AccountContactRole acr : SELECT Id, ContactID, Contact__r.AccountID 
                                      FROM AccountContactRole
                                      WHERE ContactID IN : theContacts]) {
            ContactsAccounts.add(acr.Id, acr);    
        }
        for (AccountContactRole tacr : Trigger.new) {
            for (Id key : ContactsAccounts.keyset()) {
                if (ContactsAccounts.get(key).ContactID == tacr.ContactID) {
                    if (ContactsAccounts.get(key).AccountID != tacr.AccountID) {
                        if (thisTrigger.Error__c) {
                            tacr.addError('Attempt to cross-link Contact to ' + tacr.AccountID + ', belongs to ' + ContactsAccounts.get(key).AccountID);
                        }
                    }
                }
            }
        }
    }
}

You can probably guess how far I got with that...

Error    1    SObject type does not allow triggers: AccountContactRole    C:\Projects\SalesForce\Broker\Triggers\EditAccountContactRoleSameAccount.trigger    1    1    

Is there another way I can enforce this rule?

Thanks.