-3

I am trying to write a trigger that will automatically create a campaign record when a new account is created. Below is my code:

trigger AddCampaign on Account(after insert) {
    
    List<Campaign> myCamp = new List<Campaign>();
 
    for(Account a : Trigger.New) {
        
        myCamp.add(new Campaign(Name=a.Name + ' Campaign',
                                Type='Webinar',
                                StartDate=System.today().addMonths(1)
                                ));
    }
     
    insert myCamp;
}

For some unknown reason the code is not working and it is not showing any error as well. Please help.

1
  • 4
    Please edit your post to describe what is not working and how you have searched for the campaigns that were created. Also remember that you have to set the IsActive field so the campaigns will appear in lookup searches. Jul 2, 2021 at 23:33

2 Answers 2

1

Try the below code, it should work. And also to share a note, Campaigns and Accounts are tied to each other when contacts are added as CampaignMembers. So if just the campaign is created, there will be no change on the related tab.

trigger AutoInsertCampaign on Account (before insert) {
    List<Campaign> myCamp = new List<Campaign>();
    Date nextMonth = System.today().addMonths(1);
    
    for(Account a : Trigger.New) {
        Campaign newCampaign = new Campaign();
        newCampaign.put('Name', a.Name + ' Campaign');
        newCampaign.put('Type', 'Webinar');
        newCampaign.put('StartDate', nextMonth);
        newCampaign.put('StartDate', nextMonth);
        myCamp.add(newCampaign);
    }
    
    Database.insert(myCamp, false);
}
0

It should create campaigns. However the default All View displays only active campaigns. So you might want to set the field "IsActive" on Campaign to true in your code.

Not the answer you're looking for? Browse other questions tagged or ask your own question.