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
afgmsafgms 

Create Apex Batch Job to update multiple objects

Hello Friends. I hope you're well.
I'm new in Apex so I would like to have your input regarding how to handle this requirement that I have to complete.

A new CustomObject that will be created in order to be filled with records that represents update instructions that needs to be performed. The Custom Object will have the following fields: SObject (were the update is to be performed), the SObjectID (ID of the record), Field (Name of the field in the SObject) and Value (Value to be applied in the update).

So, if the user adds the following record in the Custom Object:
sObject - Account
SObjectID - 221hdi21u213
Field - Name
Value - David

The process when is executed (it will be scheduled), the record is fetched and a update will performed in Account (to change the value for the field Name, for the record ID 221hdi21u213)

In this case, I know that I need a Scheduler Apex class and Batchable class. Since the aim is to be flexible and be able to add multiple records (and multiple objects), what should be the best approach to handle this?

Thanks a lot!

 
Best Answer chosen by afgms
Prateek Prasoon 25Prateek Prasoon 25
One possible approach to handle this scenario is to create a custom Batchable class that will retrieve the records from the Custom Object and perform the necessary updates on the corresponding SObject records. Here are the high-level steps for implementing this approach:
Define a custom object that will hold the update instructions. As you mentioned, this object will have fields for the SObject name, record ID, field name, and field value.
Create a batch job that will retrieve the update instructions from the custom object and perform the necessary updates. The batch job can be scheduled to run at a certain interval, or you can trigger it manually.
In the execute method of the batch job, query the custom object to retrieve the update instructions. Use the SObject name and record ID to retrieve the corresponding record, and update the specified field with the new value.
To make the batch job flexible and able to handle updates on multiple objects, you can use a dynamic SOQL query to retrieve the records based on the SObject name and record ID. You can also use the Database.update method to perform the updates, which will work for any SObject type.
Here's an example of what the Batchable class could look like:
public class UpdateInstructionsBatch implements Database.Batchable<SObject> {

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([
            SELECT Id, SObject__c, SObjectID__c, Field__c, Value__c
            FROM Update_Instructions__c
        ]);
    }

    public void execute(Database.BatchableContext context, List<Update_Instructions__c> instructions) {
        List<SObject> recordsToUpdate = new List<SObject>();
        for (Update_Instructions__c instruction : instructions) {
            String sObjectName = instruction.SObject__c;
            String recordId = instruction.SObjectID__c;
            String fieldName = instruction.Field__c;
            Object fieldValue = instruction.Value__c;

            // Use dynamic SOQL to retrieve the record to update
            SObject record = Database.query(
                'SELECT Id, ' + fieldName + ' FROM ' + sObjectName + ' WHERE Id = \'' + recordId + '\''
            );
            if (record != null) {
                // Update the record and add it to the list of records to update
                record.put(fieldName, fieldValue);
                recordsToUpdate.add(record);
            }
        }

        // Perform the updates
        Database.update(recordsToUpdate, false);
    }

    public void finish(Database.BatchableContext context) {
        // Optionally, perform any cleanup or logging here
    }
}

If you find this answer helpful, Please mark it as the best answer.

All Answers

Prateek Prasoon 25Prateek Prasoon 25
One possible approach to handle this scenario is to create a custom Batchable class that will retrieve the records from the Custom Object and perform the necessary updates on the corresponding SObject records. Here are the high-level steps for implementing this approach:
Define a custom object that will hold the update instructions. As you mentioned, this object will have fields for the SObject name, record ID, field name, and field value.
Create a batch job that will retrieve the update instructions from the custom object and perform the necessary updates. The batch job can be scheduled to run at a certain interval, or you can trigger it manually.
In the execute method of the batch job, query the custom object to retrieve the update instructions. Use the SObject name and record ID to retrieve the corresponding record, and update the specified field with the new value.
To make the batch job flexible and able to handle updates on multiple objects, you can use a dynamic SOQL query to retrieve the records based on the SObject name and record ID. You can also use the Database.update method to perform the updates, which will work for any SObject type.
Here's an example of what the Batchable class could look like:
public class UpdateInstructionsBatch implements Database.Batchable<SObject> {

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([
            SELECT Id, SObject__c, SObjectID__c, Field__c, Value__c
            FROM Update_Instructions__c
        ]);
    }

    public void execute(Database.BatchableContext context, List<Update_Instructions__c> instructions) {
        List<SObject> recordsToUpdate = new List<SObject>();
        for (Update_Instructions__c instruction : instructions) {
            String sObjectName = instruction.SObject__c;
            String recordId = instruction.SObjectID__c;
            String fieldName = instruction.Field__c;
            Object fieldValue = instruction.Value__c;

            // Use dynamic SOQL to retrieve the record to update
            SObject record = Database.query(
                'SELECT Id, ' + fieldName + ' FROM ' + sObjectName + ' WHERE Id = \'' + recordId + '\''
            );
            if (record != null) {
                // Update the record and add it to the list of records to update
                record.put(fieldName, fieldValue);
                recordsToUpdate.add(record);
            }
        }

        // Perform the updates
        Database.update(recordsToUpdate, false);
    }

    public void finish(Database.BatchableContext context) {
        // Optionally, perform any cleanup or logging here
    }
}

If you find this answer helpful, Please mark it as the best answer.
This was selected as the best answer
afgmsafgms
Hello Prateek Prasoon 25,
Thank you for your response.

Regarding the requirement, I will have other field that if is filled, I will need to perform other SOQL query for validation. So, for each record I will perform 1 or 2 SOQL queries. Having the dynamic SOQL queries inside of the loop instruction, it will not cause issues regarding reaching Governor limits for SOQL queries?  Or should I limit the Batch Size per chuck for a lower value (for example 100)?

Many thanks for your help!