+ Start a Discussion
levi6dblevi6db 

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

 

Best Answer chosen by Admin (Salesforce Developers) 
levi6dblevi6db

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

 

 

Message Edited by levi6db on 12-29-2009 02:37 PM

All Answers

ToddKruseToddKruse

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 

levi6dblevi6db

Thanks for the guidance Todd.  How do you add additional for loops?  I already have the (for Task t: Trigger.new)?

 

Alex

levi6dblevi6db

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

 

 

Message Edited by levi6db on 12-29-2009 02:37 PM
This was selected as the best answer