+ Start a Discussion
admin awadmin aw 

APEX Code for updating lookup field based on picklist list value on opportunity

Hi,

 

I am not a developer and it's hard for me to create even a simple Apex code.

Can somebody post a simple APEX trigger to update lookup field based on the picklist value field.

What I am looking for is to update:

Campaign Source (custom lookup field on opportunity) to a specific campaign name "Marketing Campaign" if lead source field (picklist ) is "Marketing Lead".

Thank you

swatKatswatKat

You can use this :

 

trigger updateCampaignSource on Opportunity (before update) {
    
    List<Campaign> lstCampaign=[Select Id from Campaign where Name='Marketing Campaign'];
    if(!lstCampaign.isEmpty()){
        for(Opportunity opp:Trigger.New){
            if(opp.LeadSource=='Marketing Lead' && opp.Campaign_Source__c!=lstCampaign[0].Id){
                opp.Campaign_Source__c=lstCampaign[0].Id;
            }
        }
    }
}

 

admin awadmin aw

Thank you,SwatKat

 

I've tested it in the Sandbox and  it gives me the syntax error. I am sorry,
"primary campaign source" field is a standard SF field,not sure if it makes a difference.

Error is in line # 6

trigger updateCampaignSource on Opportunity (before update) {
    
    List<Campaign> lstCampaign=[Select Id from Campaign where Name='Web Lead'];
    if(!lstCampaign.isEmpty()){
        for(Opportunity opp:Trigger.New){
            if(opp.LeadSource=='Web Lead' && opp.Primary Campaign Source!=lstCampaign[0].Id){
               =lstCampaign[0].Id;
                opp.Primary Campaign Source =lstCampaign[0].Id;
            }
        }
    }
}

 Error msg  is "expecting right paratheses, found "Campaign"

Can you please help?

 

Thank you.

 

Avidev9Avidev9
if(opp.LeadSource=='Web Lead' && opp.CampaignId!=lstCampaign[0].Id){
               
                opp.Primary Campaign Source =lstCampaign[0].Id;
            }
admin awadmin aw

Thank you.

Now it says "Expected semi-colon,found Source"

swatKatswatKat

if(opp.LeadSource=='Web Lead' && opp.CampaignId!=lstCampaign[0].Id){

opp.CampaignId =lstCampaign[0].Id;
}

admin awadmin aw

Thank you,SwatKat.

 

I got syntax to work, but trigger doesn't work...it doesn't update Primary Campaign Source.

 

Can you please check the logics:

 

trigger updateCampaignSource on Opportunity (before update)
{
List<Campaign> lstCampaign=[Select Id from Campaign where Name='Web Lead'];
if(!lstCampaign.isEmpty()){
for(Opportunity opp:Trigger.New){
if(opp.LeadSource=='Web Lead' && opp.CampaignId!=lstCampaign[0].Id){

opp.campaignid =lstCampaign[0].Id;
}
}
}
}

 

Thank you