• The WordSlinger
  • NEWBIE
  • 0 Points
  • Member since 2011

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies

I have a situation where I'm trying to implement a synching of a set of information between Accounts and Contacts, regardless of which object level the information is updated. I have built out the custom code to synch Account information to all contacts when it's changed at the Account level but I'm running into weirdness in the Trigger and code when the Contact level information is updated. It should flow logically like this:

  1. Information is updated at one of the contact records
  2. The code updates the information ont he parent Account of that contact
  3. The code then queries all of the contacts related to that parentAccount and updates the information there as well

I want to prevent recursion so I need to somehow exclude the originating contact from the query in step 3.

 

Here is my trigger:

trigger ContactbeforeUpdateTrigger on Contact (before update) {
	
	List<Contact> changedContacts = new List<Contact>();
	
	for (Integer i = 0; i < Trigger.new.size(); i++) {	
			if( 
			(Trigger.old[i].Competitive_Owner__c != Trigger.new[i].Competitive_Owner__c)) {
				changedContacts.add(Trigger.new[i]);
			}
			
			if(!changedContacts.isEmpty()){
			
			ContactServices.syncContactsToAccountandRelatedContacts(changedContacts);
		}
	}
}

 

 

Here is my Apex Class and the method called from the Trigger:

public with sharing class ContactServices { 

Public static void syncContactsToAccountandRelatedContacts (List<Contact> changedContacts){
	List<Account> accountsToUpdate = new List<Account>();
	List<Contact> contactsToUpdate = new List<Contact>();
		
	for (Integer i = 0; i < changedContacts.size(); i++) {		        	
		changedContacts[i].Account.Competitive_Owner__c= changedContacts[i].Competitive_Owner__c;	  
            	accountsToUpdate.add(changedContacts[i].Account);
        }
        update accountsToUpdate;

		
	contactsToUpdate = [Select id, accountId, Competitive_Owner__c From Contact Where accountId in: 
						accountsToUpdate];
						
	for (Integer i = 0; i < contactsToUpdate.size(); i++){
	     contactstoUpdate[i]Competitive_Owner__c = contactstoUpdate[i].Account.Competitive_Owner__c ;	
	updatedContacts.add(c); 
	}
	update updatedContacts;
}