+ Start a Discussion
Chad CoffeyChad Coffey 

Create apex trigger on Opportunity to update Account based on Contact selected

I am not looking for a Process Builder as I want to this update automatically and not wait until the Record is saved for this to be updated.  Here is what I ahve started with.  Any help would be greatly appreciated!

trigger <addaccount> on Opportunity (after insert,after update) {

for (Opportunity op : [select Account.Name from Contact.id])
Best Answer chosen by Chad Coffey
Deepak GulianDeepak Gulian
trigger AddAccount on Opportunity (before insert) {
    Set<Id> ConIds = new Set<Id>();
    Map<Id, Id> conAccMap = new Map<Id,Id>();
    
    for(Opportunity o : Trigger.New) {
        ConIds.add(o.<Contact_Lookup_Field>);
    }
    
    for(Contact c: [SELECT Id, AccountId From Contact WHERE Id IN:ConIds]){
        conAccMap.put(c.Id, c.AccountId);
    }
    
    for(Opportunity ol : Trigger.New) {
        ol.AccountId = conAccMap.get(ol.<Contact_Lookup_Field>);
    }     
}

//Please replace <Contact_Lookup_Field> with the actual API name of the Contact Field in Opportunity Object.

Try this!

All Answers

Deepak GulianDeepak Gulian
trigger AddAccount on Opportunity (before insert) {
    Set<Id> ConIds = new Set<Id>();
    Map<Id, Id> conAccMap = new Map<Id,Id>();
    
    for(Opportunity o : Trigger.New) {
        ConIds.add(o.<Contact_Lookup_Field>);
    }
    
    for(Contact c: [SELECT Id, AccountId From Contact WHERE Id IN:ConIds]){
        conAccMap.put(c.Id, c.AccountId);
    }
    
    for(Opportunity ol : Trigger.New) {
        ol.AccountId = conAccMap.get(ol.<Contact_Lookup_Field>);
    }     
}

//Please replace <Contact_Lookup_Field> with the actual API name of the Contact Field in Opportunity Object.

Try this!
This was selected as the best answer
Chad CoffeyChad Coffey
Thanks Deepak, 

So unfortunately this is not working.  Although I am not getting any errors, the automatic insert of Account on the Opportuntiy based on the Contact listed, is not populating.  I changed the Contact_Lookup_Field to Hiring_Manager_C (which is the custom lookup field for Contact on the opportunity).  Any additonal help would be greatly appreciated!

User-added image
Deepak GulianDeepak Gulian

I'm running same code at my end and its working fine for newly inserted opportunities. So make sure you these things:-

- Trigger will run on insert of Opportunity

- Make sure your Contact record have Account Name.

Test it and let me know again.

Chad CoffeyChad Coffey
Deepak, 

Thanks for the help on this!