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
mxalix258mxalix258 

Updating a record from a trigger on another record

If I want to have a trigger on a record in one object, that updates a record in another object, how can I accomplish this without having  a SOQL query inside a for loop? We are going to want to map a couple fields back to the other record, so I'm not sure the most efficient way to do this. I was thinking something like this:

 

trigger ContactUpdater on Custom_Object_Name__c (after update) {

 List<Contact> Contactlist = new List<Contact>();
 List<Contact> updatedContacts = new List<Contact>();

 for(Custom_Object_Name__c p : trigger.new){

        If(p.Associated_Contact__c != Null){ 
          Contactlist.add(p.Associated_Contact__c);

          }

	for(Contact c : [SELECT Id FROM Contact WHERE Id IN :Contactlist]){
             c.FieldToUpdate = p.FieldValue;

             updatedContacts.add(c);
          }

         update updatedContacts; 

    }

 

Is there anything inherently wrong with how this is coded?

 

Naidu PothiniNaidu Pothini
trigger ContactUpdater on Custom_Object_Name__c (after update)
{
	List<Id> Contactlist = new List<Id>();
	List<Contact> updatedContacts = new List<Contact>();

	for(Custom_Object_Name__c p : trigger.new)
	{
		If(p.Associated_Contact__c != Null)
		{
			Contactlist.add(p.Associated_Contact__c);  // Collect all the contact Ids
		}
	}

	Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id FROM Contact WHERE Id IN :Contactlist]); // Create a map of contacts

	for(Custom_Object_Name__c p : trigger.new)
	{
		If(p.Associated_Contact__c != Null)
		{
// update the related contact and add to list Contact con = conMap.get(p.Associated_Contact__c); con.FieldToUpdate = p.FieldValue; updatedContacts.add(c); } } update updatedContacts; // update the List of contacts }

 try this.

mxalix258mxalix258

What would be the difference between doing that, and doing something like this:

 

trigger ContactUpdater on Custom_Object_Name__c (after update)
{
	List<Contact> updatedContacts = new List<Contact>();

	for(Custom_Object_Name__c p : trigger.new)
	{
		If(p.Associated_Contact__c != Null)
		{
                        // update the related contact and add to list
			Contact con = p.Associated_Contact__c;

			con.FieldToUpdate = p.FieldValue;

			updatedContacts.add(c);
		}
	}

	update updatedContacts; // update the List of contacts
}