Developer Beginner > Apex Triggers >Bulk Apex Triggers
Currently stuck on this problem.
Here are the instructions:
- Create an Apex trigger:
- Name: ClosedOpportunityTrigger
- Object: Opportunity
- Events: after insert and after update
- Condition: Stage is Closed Won
- Operation: Create a task:
- Subject: Follow Up Test Task
- WhatId = the opportunity ID (associates the task with the opportunity)
- Bulkify the trigger so that it can insert or update 200 or more opportunities
Here is my code:
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) { List <Task> TaskList = new List<Task>(); for (Opportunity a : Trigger.New) { if(a.StageName == 'Closed Won'){ TaskList.add(new Task(Subject= 'Follow Up Test Task', WhatId = a.id)); } } if(TaskList.size() > 0) { insert TaskList; } }
This is the error:
'We tried to insert 200 opportunities but the trigger exceeded DML limits. Make sure your code is bulkified.'
Hi Luis,
You need to put this condition outside thefor loop.
if(TaskList.size() > 0) { insert TaskList; }
Then it will work perfectly fine.