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
AntonPavlovAntonPavlov 

Help solve. Count of created My Task records must be tracked increment the value on related User (owner) record using Trigger

trigger countTack on MyTask__c (after update) {
   List<MyTask__c> myTask = [SELECT Id,(SELECT Id,CountMyTask__с FROM Contact) FROM MyTask__c WHERE Id IN :Trigger.New];
   for(MyTask__c my :myTask){
      List<Contact> contactList = my.Contacts;
      my.CountMyTask__c = contactList.size();
   }
}
Dont work
Best Answer chosen by AntonPavlov
Abdul KhatriAbdul Khatri
I can also help you with the trigger. Here is the code

Since MyTask__c is a child to Contact, The field Name will Contact__c
trigger countTack on MyTask__c (after insert, after update) {
    
    Set<Id> idContacts = new Set<Id>();
    for(MyTask__c myTask : Trigger.new){
        idContacts.add(myTask.Contact__c);
    }
    
       List<Contact> myContacts = [SELECT Id, CountMyTask__с, (SELECT Id FROM MyTask__r) FROM Contact WHERE Id IN :idContacts];
    
       for(Contact contact : myContacts){
        
        if(contact.MyTask__r != null){
            contact.CountMyTask__c = contact.MyTask__r.size();
        }
       }
    
    if(!myContacts.isEmpty()) update myContacts;
}

 

All Answers

Abdul KhatriAbdul Khatri
Is MyTask__c is the child object of the Contact?

You can achieve the same by using Roll-Up Summary field. No need for the trigger.
Abdul KhatriAbdul Khatri
Hey did you try that?
AntonPavlovAntonPavlov
Hi yes, this is a child of a Contact. But I need to use a trigger on a task condition.
Abdul KhatriAbdul Khatri
Hi,

Roll-Up Summary does give you option for the condition

User-added image
Abdul KhatriAbdul Khatri
I can also help you with the trigger. Here is the code

Since MyTask__c is a child to Contact, The field Name will Contact__c
trigger countTack on MyTask__c (after insert, after update) {
    
    Set<Id> idContacts = new Set<Id>();
    for(MyTask__c myTask : Trigger.new){
        idContacts.add(myTask.Contact__c);
    }
    
       List<Contact> myContacts = [SELECT Id, CountMyTask__с, (SELECT Id FROM MyTask__r) FROM Contact WHERE Id IN :idContacts];
    
       for(Contact contact : myContacts){
        
        if(contact.MyTask__r != null){
            contact.CountMyTask__c = contact.MyTask__r.size();
        }
       }
    
    if(!myContacts.isEmpty()) update myContacts;
}

 
This was selected as the best answer
AntonPavlovAntonPavlov

Abdul Khatri, thanks for the help