+ Start a Discussion
SalesforceBeginnerSalesforceBeginner 

Trigger to populate Lookup field on Opportunity

Hi,

 

I am new to Salesforce triggers. I want to populate the custom lookup "Contact Name" field on Opportunity screen whenever Lead gets converted.

 

Thanks,

SFBeginner

Best Answer chosen by Admin (Salesforce Developers) 
wt35wt35

Can you try the following?

 

trigger testConversion2 on Lead (after insert,after update)
{

 List<Opportunity> opps = new List<Opportunity>();
 Map<Id,Id> association = new Map<Id,Id>();
 
  for(Lead l : Trigger.new)
  {
    if(l.IsConverted && (l.ConvertedOpportunityId != null) )
    {
     association.put(l.ConvertedOpportunityId, l.ConvertedContactId);
    }
  }
  
  opps = [SELECT ContactLookup__c FROM Opportunity WHERE Id IN : association.keySet()]; 

  for (Opportunity o: opps)
  {
   o.ContactLookup__c = association.get(o.Id);
  }

update opps;

}

 

All Answers

wt35wt35

Can you try the following?

 

trigger testConversion2 on Lead (after insert,after update)
{

 List<Opportunity> opps = new List<Opportunity>();
 Map<Id,Id> association = new Map<Id,Id>();
 
  for(Lead l : Trigger.new)
  {
    if(l.IsConverted && (l.ConvertedOpportunityId != null) )
    {
     association.put(l.ConvertedOpportunityId, l.ConvertedContactId);
    }
  }
  
  opps = [SELECT ContactLookup__c FROM Opportunity WHERE Id IN : association.keySet()]; 

  for (Opportunity o: opps)
  {
   o.ContactLookup__c = association.get(o.Id);
  }

update opps;

}

 

This was selected as the best answer
Venkatesh.ax1803Venkatesh.ax1803

If you want to access the lookup object fields in the trigger context, it is not possible directly, only related field will be accessed, in order  to access all the fields, need to query the look up object.

SalesforceBeginnerSalesforceBeginner
It worked!!! :)
Thanks a lot wt35.
sudha ranisudha rani
@ wt35 i WANT TO mapp attachment of lead to opportunity
 
Christine PrestonChristine Preston
I tried the above & changed the ContactLookup__c to the custom field I have on the Opportunity & Lead of Purchasing Contact.  I am not longer receiving the error that the Opp can't be created because of the required Purchasing Contact Field, but now it isn't even creating the Opportunity at all. 

trigger testConversion2 on Lead (after insert,after update)
{
 List<Opportunity> opps = new List<Opportunity>();
 Map<Id,Id> association = new Map<Id,Id>();
  for(Lead l : Trigger.new)
  {
    if(l.IsConverted && (l.ConvertedOpportunityId != null) )
    {
     association.put(l.ConvertedOpportunityId, l.ConvertedContactId);
    }
  }
  opps = [SELECT Purchasing_Contact__c FROM Opportunity WHERE Id IN : association.keySet()];
  for (Opportunity o: opps)
  {
   o.Purchasing_Contact__c = association.get(o.Id);
  }
update opps;
}