0

New to Apex development so I wouldn't be surprised if I'm missing something obvious here. Anyways I'm trying to write a trigger that adds a task to an opportunity once it is created (and sets the due date to be six months in the future). Here's what I have:

trigger FollowUp on Opportunity (after insert) {
    List<Task> taskList = new List<Task>();

    for (Opportunity Opp: trigger.new) {
        Task t = new Task();
        t.whatID = opp.ID;
        t.Subject = 'Follow up with Report';
        Date dueDate = opp.CloseDate;
        t.ActivityDate = dueDate.addmonths(6);
        taskList.add(t);
    }
}

However, after I save this, I have tried creating a new opportunity, and no task is created.

My two questions are:

1) What is wrong with this specific code, why is it not creating a new task on the donation?

2) In the future, what tools are available to me in SF to diagnose why Apex code is not working? Are errors saved anywhere?

Thank you very much!

  • 2
    I don't see an insert taskList; after the for loop. You could refer this: Apex best practices as a start for your Apex development. – Arnold Jr. May 7 '18 at 16:30
  • have you inserted the taskList with an insert statement? That can be an easy miss. – Ashish Sharma May 7 '18 at 16:31
  • You were both right :( I forgot the insert! Thank you for the best practices link. – James May 7 '18 at 16:53
5

What is wrong with this specific code, why is it not creating a new task on the donation?

You didn't actually call the code that commits data to the database, as in:

insert taskList;

Which you should do outside of the for loop, before the end of your code.

In the future, what tools are available to me in SF to diagnose why Apex code is not working? Are errors saved anywhere?

There is no system error in this case, it was a logic error. These can be hard to track down until you learn more about writing code. I suggest going through the developer modules on Trailhead.

Once you know what you're looking for, you'll find we have an array of features we can use: Unit tests for testing our logic, the Debug Logs for reading what happened, the Check Point system for examining memory at a specific point in your code, and the Apex Debugger (available for an extra cost) for an interactive debugging session.

  • Ah! Perfect, thank you! Now it works. I appreciate the links and will spend some time digging in. – James May 7 '18 at 16:52
1

put this line after your for loop. insert taskList;. this will create task records into database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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