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
KSTNEKSTNE 

First time writing a trigger, need some help

Hi guys,

 

Here is the scenario. We have two objects, Contacts and Opportunity. Contact has Latitude__c and Longitude__c fields and so does the Opportunity.

 

We want to populate the fields Latitude__c and Longitude__c in Contact as soon as those fields are filled in Opportunity. I guess this is a cross-object field update ?

 

The code below is what I have at the moment, but I'm not sure if I'm doing it right. Any help or ideas are welcome.

 

 

trigger Contact_Update on Opportunity (after insert) {

    try {
        if (trigger.new.size()==1){
        	
           //for(Opportunity O : Trigger.new) {
               Contact cnt = new Contact();
               Opportunity Op = new Opportunity();
               
			   cnt.Longitude__c = Op.longitude__c;
			   cnt.Latitude__c = Op.latitude__c;
			   
			   update cnt;
           //}
        }
    } catch(Exception e) {
        system.debug ('error: ' + e.getMessage() );
    }
    
}

 

Thanks

 

sfdcfoxsfdcfox

Your code isn't bulkified (but that's "okay", since you're testing this against just a single record, apparently). Secondly, you have no idea what contact you're updating (there's no Contact ID), so your trigger will always through an exception; your try-catch block will stop the system from halting, but it won't work.

 

Assuming you have a Contact__c field on the opportunity, you could do this:

 

trigger ContactUpdate On Opportunity (After Insert) {
    Map<Id, Contact> contacts = new Map<Id, Contact>();
    for(Opportunity record: Trigger.new) {
        if(record.Contact__c != null) {
             contacts.put(record.Contact__c, new Contact(Id=record.Contact__c, Longitude__c=record.Longitude__c, Latitude__c=record.Latitude__c));
        }
    }
    Database.update(contacts.values(), false);
}

I'll leave it up to you to figure out how to handle errors; this code doesn't address that problem.