You need to sign in to do that
Don't have an account?
Need help with a trigger.
Hi all,
I need to create a trigger on the Task object that changes the "Related To" field from a custom object (ABC Products) to the Opportunity associated to the custom object on creation.
Three object are being referenced:
1. Task
2. Opportunity
3. ABC Products (custom object)
The following Trigger does what I need it to do, but it is also effecting ALL Tasks, not just the ones that meet the criteria.
Can someone help me out here and explain how to limit the trigger to just the qualified Tasks?
Here is what I have so far:
trigger taskupdate on Task (before insert, before update) { List<ABC_Product__c> ablist = new List<ABC_Product__c>(); for(Task t: Trigger.new){ ABC_Product__c ab = [Select id, Opportunity_Name__c from ABC_Product__c where id = :t.WhatId]; t.WhatId = ab.Opportunity_Name__c; ablist.add( ab ); } update ablist; }
Any help would be appreciated.
Thanks,
Alex
I believe I figured it out:
trigger taskupdate on Task (before insert, before update) {
List<ABC_Product__c> ablist = new List<ABC_Product__c>();
for(Task t: Trigger.new){
if ((t.Subject == 'Fiber Approved') &&
(t.Status == 'Completed'))
{ABC_Product__c ab = [Select id, Opportunity_Name__c from ABC_Product__c where id = :t.WhatId];
t.WhatId = ab.Opportunity_Name__c;
ablist.add( ab );
}
update ablist;
}
Thanks again Todd!
Alex
All Answers
Alex,
Since you only want to be affecting certain records and not all the existing records, you will need to do some sort of filtering. Perhaps in the for loop a check on the current task item to see if its a record you want to update, if so, do the update otherwise skip it.
Hope that helps.
Todd Kruse
Thanks for the guidance Todd. How do you add additional for loops? I already have the (for Task t: Trigger.new)?
Alex
I believe I figured it out:
trigger taskupdate on Task (before insert, before update) {
List<ABC_Product__c> ablist = new List<ABC_Product__c>();
for(Task t: Trigger.new){
if ((t.Subject == 'Fiber Approved') &&
(t.Status == 'Completed'))
{ABC_Product__c ab = [Select id, Opportunity_Name__c from ABC_Product__c where id = :t.WhatId];
t.WhatId = ab.Opportunity_Name__c;
ablist.add( ab );
}
update ablist;
}
Thanks again Todd!
Alex