+ Start a Discussion
Brenda Frambes 10Brenda Frambes 10 

Create trigger to update custom object fields when a task is Opened

I have created a custom object Project__c.  When a record is created on this object a series of Tasks are created.  As tasks are closed other tasks are opened.  I would like to update two fields on Project_C with the most recent Open Task.  The field names on the Object are:  Stage__c and Sub_Stage__c,  the fields on the tasks are:  Project_Stage__c and Project_Sub_Stage__c

So when a Task status changes to Open,
Stage__C = Project_Stage__c
Sub_Stage__C = Project_Sub_Stage__C

I'm trying to learn APEX to be able to do this myself but my skills aren't up to speed for this.  Any help would be GREATLY appreciated.  Thank you
Try this, 
trigger UpdateProject_Task on Task (after update) {
	List<Project__c> projects= new List<Project__c>();
    Map<Id, Task> pMap= new Map<Id, Task>();
    for(Task t :Trigger.New){
        //Make sure status was changed to Open from something else and subject is something - to limit the updates to only Project__c related tasks
        if(t.Status == 'Open' && Trigger.oldMap.get(t.Id).Status != 'Open' && t.Subject == 'Project Task'){
            pMap.put(t.WhatId, t);
    if(pMap.size() > 0){
        Set<Id> pIds= pMap.keySet();
         projects=[SELECT Id, Stage__C, Sub_Stage__C FROM Project__c WHERE Id IN :pIds];
        for(Project__c p :projects){
            p.Stage__C = pMap.get(p.Id).Project_Stage__c;
            p.Sub_Stage__C = pMap.get(p.Id).Project_Sub_Stage__C;
        update projects;

Rohit Sharma 66Rohit Sharma 66
Try following code:

trigger updateAccountOpenTask on Task (before update) {
   List<Project__c> projectList = new list<Project__c>();    
   for(task taskRecord : trigger.new){
       if(Trigger.oldMap.get(taskRecord.Id).Status == 'Closed') {
           If(Trigger.newMap.get(taskRecord.Id).Status == 'Open'){
               for(Project__c proj : [Select Id, Stage__c, Sub_Stage__c from Project__c where Id =: taskRecord.Project__c]){
                   proj.Stage__c = taskRecord.Subject;
                   proj.Sub_Stage__c = taskRecord.Subject;
       update projectList;

You can add the condition to find recentlu updated task

Let me know if this helps.
Brenda Frambes 10Brenda Frambes 10
Thank you both!  I will try and let you know which way I go with