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
Bryan Leaman 6Bryan Leaman 6 

Identify specific batch job that created records

We use a managed package that uses a batch job to create records. But they don't provide any field to group those records together to see what any specific batch job created them. 

I would like to be able to create a trigger that could identify that the records are being created from a batch run (System.isBatch()) and then use the batch job Id to tie all those records together. So far I don't see any way to obtain this information in a trigger.

Ideally, I'd be able to do something like:
trigger on pkg__PackageObject__c (before insert) {
if (System.isBatch()) {
    Id batchId = System.getBatchJobId();
    for(pkg__PackageObject__c rcd : Trigger.new) {
        rcd.batch_job_id__c = batchid;
    }
}
But I can't find any such thing as "System.getBatchJobId()". I've found no way to instantiate Database.BatchableContext to peer into the current batch process being run.
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Bryan,

We cannot get running job id in the trigger. We can only get whether if the execution is from batch or not using System.isBatch(). 

You may need to have some field to update that it is created from the batch. .

Please find the below question (https://salesforce.stackexchange.com/questions/70500/how-to-detect-the-name-or-id-of-currently-running-batch-job-from-trigger) which i similar to the one you raised.

If this solution helps, Please mark it as best answer.

Thanks,
Bryan Leaman 6Bryan Leaman 6
If anyone else would like to see this capability added to Apex, please up-vote this idea:
https://ideas.salesforce.com/s/idea/a0B8W00000LzGHFUA3/retrieve-current-batch-context-in-other-classes-and-triggers