3

I have written a batch which stamps the first activity date on contact records with the first created date of task or event on that record.

My SOQL query is excluding tasks with Allow Users to Relate Multiple Contacts to Tasks and Events. Can anyone help me where I am going wrong or help me with a different approach to overcome this problem.

I have also used ALL ROWS keyword here. Actual record shows task but SOQL results do not.

global class BatchUpdateFirstActivityOnContact implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'select Id,(select Id,createddate from tasks order by createddate limit 1),(select Id,createddate from events order by createddate limit 1) from Contact where id=\'0030e00002JzYay\' ALL ROWS';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<contact> contacts) {
        List<Contact> ContactsToUpdate = new List<Contact>(); 
        for(Contact c:Contacts){
            if(c.tasks.size()>0 && c.events.size()>0){
                if(c.tasks[0].Createddate < c.events[0].Createddate){
                    ContactsToUpdate.add(new Contact(Id=c.Id,First_Activity_Date__c = c.tasks[0].Createddate));
                }else if(c.tasks[0].Createddate > c.events[0].Createddate){
                    ContactsToUpdate.add(new Contact(Id=c.Id,First_Activity_Date__c = c.events[0].Createddate));
                }
            }else if(c.tasks.size()>0 && c.events.size()==0){
                ContactsToUpdate.add(new Contact(Id=c.Id,First_Activity_Date__c = c.tasks[0].Createddate));
            }else if(c.tasks.size()==0 && c.events.size()>0){
                ContactsToUpdate.add(new Contact(Id=c.Id,First_Activity_Date__c = c.events[0].Createddate));
            }
        }

        update ContactsToUpdate; 
    }
    global void finish(Database.BatchableContext BC) {

    }
}
4
  • Can you be more specific about what results you are not getting? I would expect that what you're seeing is that you only get back Tasks where the Contact is the primary (first) WhoId. Is that correct?
    – David Reed
    May 29, 2019 at 13:54
  • 1
    Hi, Yes. if the task is related to only one contact...I see the results. But if the tasks are realted to multiple contacts then results are null. May 29, 2019 at 14:00
  • Results are null? sObject queries never return null, but they can return an empty list. Could you please edit your question to provide one or more concrete examples?
    – David Reed
    May 29, 2019 at 14:01
  • Sorry my bad. Yes empty results. May 29, 2019 at 14:03

0

You must log in to answer this question.

Browse other questions tagged .