+ Start a Discussion
cmaine3cmaine3 

Trigger on Task when Complete Field Update

Hi There!

 

I have a need to update a date field on an opportunity when the task status is changed to completed.Workflow as follows:

 

Task marked "Completed" > Field "Follow up date" = TODAY() + 5

 

Pretty simple, but I will be using this trigger as framework for other triggers to get all our reps in line to follow through with a process, so it's pretty important. Thanks anyone who's willing to help.

 

 

Best Answer chosen by Admin (Salesforce Developers) 
sravusravu

Try the following code:

 

trigger updateOpportunityOnTaskComplete on Task (after update) {
    public Id oppId;
    for(Task t:Trigger.New){
        if(t.Status=='Completed'){
            oppId = t.WhatId;
        }
    }
    List<Opportunity> opp = [select Id from Opportunity where id = :oppId];
    for(Opportunity o : opp){
        o.Follow_Up_Date__c = system.today()+5;
        update o;
    }
   
}

 

Let me know if you face any difficulty...................

 

Hope this helps you.

All Answers

sravusravu

Try the following code:

 

trigger updateOpportunityOnTaskComplete on Task (after update) {
    public Id oppId;
    for(Task t:Trigger.New){
        if(t.Status=='Completed'){
            oppId = t.WhatId;
        }
    }
    List<Opportunity> opp = [select Id from Opportunity where id = :oppId];
    for(Opportunity o : opp){
        o.Follow_Up_Date__c = system.today()+5;
        update o;
    }
   
}

 

Let me know if you face any difficulty...................

 

Hope this helps you.

This was selected as the best answer
MicrobeMicrobe

I see a couple problems with your code:

 

- It will execute regardless of the parent. It's not checking to make sure it's an opportunity task

- If handed a list of tasks, it will only operate on the first one it finds with a "Completed" status, and ignore the remainder

 

sravusravu

you can check the task before you update the opportunity i.e. whether the trigger's WhatID is opportunity or not.

And moreover it will update if the follow up date on all the opportunity tasks.


You can check : What.Type='Opportunity'

cmaine3cmaine3

Awesome, works great. I made a few changes. Any comments?

 

 

trigger update30DayNoticeSentOnTaskComplete on Task (after update) {
    public Id oppId;
    for(Task t:Trigger.New){
        if(t.WhatId != NULL)
        if(t.Subject=='Send Out Notice To Vacate')
        if(t.Status=='Completed'){
            oppId = t.WhatId;
        }
    }
    List<Opportunity> opp = [select Id from Opportunity where id = :oppId];
    for(Opportunity o : opp){
        o.X30_Day_Letter_Sent__c = system.today()+5;
        update o;
    }
   
}