0

In our environment, it's a business rule that every contact in the contact roles array for accounts or cases must be a contact that actually belongs to that account. So I wrote a trigger to prevent cross linkage...

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);
                        }
                    }
                }
            }
        }
    }
}

Of course, 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.

0

This is, I admit, an imperfect workaround:

  1. Add a VF page to your standard Account layout
  2. The VF page must be associated to an Account standard controller extension
  3. The VF page displays a message in big red letters indicating which account contract roles violate the rule (the controller extension does the query from the current Account to all the children). If no issue, display a benign 'all is well' message

The workaround is imperfect because it doesn't handle batch updates via DataLoader or some other client API and it assumes the user will act on your warning message (maybe use 1994-style annoying, flashing letters).

A more robust, but messy, alternative is to replace the way Account Contact Roles are added with your own custom button, VF page and related list. The Account page itself will most likely need to be replaced as well with a VF page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.