function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
M.MehtabM.Mehtab 

Apex Trigger to update Custom Field on Task

I am very new to Apex development and this is my very first trigger. I am trying to update a custom field 'No_on_Call__c' on Tasks which counts the number of people that are on the call since we activated the Shared Activites feature recently.

When saving a test task the trigger gives me a SELF REFERENCE error and says it cannot recursively update itself. It makes sense but i just cannot figure out how to fix this and it is frustrating me no end.

 

Here is the code:

 

trigger Numberofcalls on Task (before insert,before update) {

Integer i=0;

// Get TaskID

String TskID= Trigger.new[i].Id;

list<TaskRelation> Tsr= [SELECT RelationId  FROM TaskRelation WHERE TaskId = :TskID];

list<Task> Tsk= [Select No_on_Call__c FROM Task WHERE Id =: TskId];

for (Task o : Tsk) {
                Integer count = Tsk.size();

                if (o.No_on_Call__c != count) {
                    o.No_on_Call__c = count;
                   
                }
         Update o;       
           
            }
            
}

PrakashbPrakashb

On before update triggers you dont need to use the update statement.

 

You can simply remove the update statement.

vishal@forcevishal@force

Yes, in a BEFORE trigger, your code gets executed just before the record is actually committed in the database. So after it's execution, it will get updated or inserted. So you do not need to specify the dml statement in a before trigger.

 

 

for (Task o : Tsk)

{
                Integer count = Tsk.size();

                if (o.No_on_Call__c != count)

               {
                    o.No_on_Call__c = count;
                   
                }

}

 

That should do it for you!

TrinayTrinay

Hi Mehtab,

 

   Please make the following changes in your trigger:

 

trigger:

---------

trigger Numberofcalls on Task (after insert,after update)

{
       Integer i=0;
       // Get TaskID
       String TskID= Trigger.new[i].Id;
       list<TaskRelation> Tsr= [SELECT RelationId  FROM TaskRelation WHERE TaskId = :TskID];
       list<Task> Tsk= [Select No_on_Call__c FROM Task WHERE Id =: TskId];
       for (Task o : Tsk)

       {
                Integer count = Tsk.size();

                
                if (o.No_on_Call__c != count)

                {

                     Task t = [SELECT id,No_on_Call__c FROM Task WHERE id = :o.id];
                      t.No_on_Call__c = count;

                      Update t;    
                 }          
        }
}

 

If this post is helpful to your solution, kindly mark this as the solution