You need to sign in to do that
Don't have an account?
dlCamelot
Trigger Fix? Child Record created based on Parent Record Insert/Update
Hi All,
I am trying to draft a my first trigger from scratch (up to this point, I have only been tweaking code already in existance). I'm struggling to develop a multi-object trigger. I would like a child record (task) to be created upon a parent record meeting certain criteria. Here's the work so far:
trigger ClosedOpportunityTask on Opportunity (after insert,after update) {
//Maps,Sets,Lists to Be Used
Set<Id> oppIds = new set<Id>();
Map<Id,Opportunity> mapTask2Opp = new map<Id,Opportunity>();
List<Task> taskList = new List<Task>();
//Bulk Trigger Loop
for (Opportunity o: trigger.new){
oppIds.add(o.Id);
mapTask2Opp.put(o.id, o);
}
//Tasks to be Created
taskList = [SELECT Id, Subject FROM Task WHERE whatid IN : oppIds];
//Create new task only if one doesn't already exist
if(taskList.size()= 0){
for(Task t: Tasklist){
t.What = ? //needs to get the parent opp's id
t.Subject = 'Follow Up Test Task';
}
update taskList;
}
}
Right now, my logic for finding records without tasks 'taskList.size()= 0' is not effective, nor do I have a good way to link the task back to the parent via the 'Related To' field (API = 'What').
Can anyone lead me in the right direction for fixing? If you can, please also explain why. I'd really like to learn from my mistakes! :)
I am trying to draft a my first trigger from scratch (up to this point, I have only been tweaking code already in existance). I'm struggling to develop a multi-object trigger. I would like a child record (task) to be created upon a parent record meeting certain criteria. Here's the work so far:
trigger ClosedOpportunityTask on Opportunity (after insert,after update) {
//Maps,Sets,Lists to Be Used
Set<Id> oppIds = new set<Id>();
Map<Id,Opportunity> mapTask2Opp = new map<Id,Opportunity>();
List<Task> taskList = new List<Task>();
//Bulk Trigger Loop
for (Opportunity o: trigger.new){
oppIds.add(o.Id);
mapTask2Opp.put(o.id, o);
}
//Tasks to be Created
taskList = [SELECT Id, Subject FROM Task WHERE whatid IN : oppIds];
//Create new task only if one doesn't already exist
if(taskList.size()= 0){
for(Task t: Tasklist){
t.What = ? //needs to get the parent opp's id
t.Subject = 'Follow Up Test Task';
}
update taskList;
}
}
Right now, my logic for finding records without tasks 'taskList.size()= 0' is not effective, nor do I have a good way to link the task back to the parent via the 'Related To' field (API = 'What').
Can anyone lead me in the right direction for fixing? If you can, please also explain why. I'd really like to learn from my mistakes! :)
try this code :-
Thanks
Anil.B
For clarification, what does "opportunity op:mapTask2Opp.values()" in the FOR loop look for?
your correct its not working for bulk records.
mapTask2Opp.values() it contains opportunity object which i am putting on the top.
try these code its working:-
Thanks
Anil.B