You need to sign in to do that
Don't have an account?
Atul Shendge 2
Need to create custom batch apex to populate a new custom numeric field (Count_c) on the account object to denote the number of emails sent to the account.
Hi Team,
Need to create custom batch apex to populate a new custom numeric field (Count_c) on the account object to denote the number of emails sent to the account.
Requirement:
We have an object Emailtarns_c where email sent are stored. Below is the query.
Select OCE__Account__r.name, count (OCE__Emailplate__r.name) from OCE__EmailTrans__c group by OCE__Account__r.name limit 10
Regards,
Atul
global Database.QueryLocator start(Database.BatchableContext BC) {
// Your query to get the count of emails sent per account
return Database.getQueryLocator([SELECT OCE__Account__r.Id, count(OCE__Emailplate__r.name) FROM OCE__EmailTrans__c GROUP BY OCE__Account__r.Id]);
}
global void execute(Database.BatchableContext BC, List<SObject> scope) {
// Create a map to store the count of emails sent per account
Map<Id, Integer> emailCountMap = new Map<Id, Integer>();
for (SObject s : scope) {
AggregateResult ar = (AggregateResult)s;
Id accountId = (Id)ar.get('OCE__Account__r.Id');
Integer count = (Integer)ar.get('expr0');
emailCountMap.put(accountId, count);
}
// Update the accounts with the email count
List<Account> accountsToUpdate = new List<Account>();
for (Account a : [SELECT Id FROM Account WHERE Id IN :emailCountMap.keySet()]) {
a.Count_c = emailCountMap.get(a.Id);
accountsToUpdate.add(a);
}
update accountsToUpdate;
}
global void finish(Database.BatchableContext BC) {
// Send an email or log a message to indicate that the batch job has finished
}
}
All Answers
global Database.QueryLocator start(Database.BatchableContext BC) {
// Your query to get the count of emails sent per account
return Database.getQueryLocator([SELECT OCE__Account__r.Id, count(OCE__Emailplate__r.name) FROM OCE__EmailTrans__c GROUP BY OCE__Account__r.Id]);
}
global void execute(Database.BatchableContext BC, List<SObject> scope) {
// Create a map to store the count of emails sent per account
Map<Id, Integer> emailCountMap = new Map<Id, Integer>();
for (SObject s : scope) {
AggregateResult ar = (AggregateResult)s;
Id accountId = (Id)ar.get('OCE__Account__r.Id');
Integer count = (Integer)ar.get('expr0');
emailCountMap.put(accountId, count);
}
// Update the accounts with the email count
List<Account> accountsToUpdate = new List<Account>();
for (Account a : [SELECT Id FROM Account WHERE Id IN :emailCountMap.keySet()]) {
a.Count_c = emailCountMap.get(a.Id);
accountsToUpdate.add(a);
}
update accountsToUpdate;
}
global void finish(Database.BatchableContext BC) {
// Send an email or log a message to indicate that the batch job has finished
}
}
Id batchId = Database.executeBatch(emailCountBatch);