Trigger to create a campaign when an account is created

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.

Answers 2

  • 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);
    }
    

  • 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.


Related Questions