Search code examples
salesforceapex-codeapex

Apex Batch Class to update Contact field from custom object field


I have an apex batch class which I need to update a contact boolean field 'Active_Subscriptions__c' based on the state of a related custom object field.

The custom object 'Subscriptions__c' has a 'Contact__c' master detail field, and also has a 'IsActive__c' boolean field.

I want to run a batch that will find any subscriptions that are related to a contact record by Id. If it finds any subscriptions that are active, it needs to set the 'Active_Subscriptions__c' on the contact record to true, else set to false.

I am fairly new to apex and can't seem to get this to trigger the results I need, thanks in advance.

global class BatchContactUpdate implements Database.Batchable<sObject>{

    List <Subscription__c> mapSubs = new List <Subscription__c> ();
    List <Contact> contactlist = new List <Contact> ();

    global Database.QueryLocator start(Database.BatchableContext BC) {
        return DataBase.getQueryLocator([SELECT Id, Contact__c FROM Subscription__c WHERE Contact__c =:contactlist]);
    }

    global void execute(Database.BatchableContext BC , List <Subscription__c> mapSubs) {
        for (Subscription__c sub : mapSubs){ 
            for (Contact con : contactList){

                if (con.Id == sub.Contact__c && sub.IsActive__c == true){
                        contactlist.add(new Contact(
                            Active_Subscriptions__c = true
                           ));
                    } else {

                        contactlist.add(new Contact(
                            Active_Subscriptions__c = false
                           ));

                    }

            }   
       }

         update contactlist;
    } 

    global void finish(Database.BatchableContext BC){

    }

}

Solution

  • Looks like you contact list is empty to start off with, so it wont return any results. But for your query, why dont you do something like

    [SELECT Id, (SELECT Id FROM Subscriptions__r WHERE Is_Active__c = true) FROM Contact];
    

    and in your execute do

    List<Contact> cList = new List<contact>();
    for(Contact c : scope){
       c.Active_Subscriptions__c = c.Subscriptions__r.size() > 0;
       cList.add(c);
    }
    //etc... to start