User Story
As a developer,
I want to write a code that updates the counts of primary, secondary, and tertiary contacts for each account, So that the account records accurately reflect the distribution of contacts.
Acceptance Criteria:
- Create three new custom fields on the Account object:
Primary Contacts
, Secondary Contacts
, Tertiary Contacts
.
- Implement logic to update these fields based on the contacts associated with each account:
- Primary Contacts: Count of contacts marked as primary contacts.
- Secondary Contacts: Count of contacts marked as secondary contacts.
- Tertiary Contacts: Count of contacts marked as tertiary contacts.
Note: Use Aggregate Results
Codes
public class AggregateResultforAccount {
public static void UpdateAccount() {
List<String> levels = new List<String>{'Primary', 'Secondary', 'Tertiary'};
Map<Id, Account> accounts = new Map<Id, Account>([SELECT Id, Primary_Contacts__c, Secondary_Contacts__c,Tertiary_Contacts__c
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact) ]);
for (String level : levels) {
List<AggregateResult> primary = [SELECT AccountId acID, Count(Id) TOTAL FROM Contact WHERE Level__c = :level GROUP BY AccountId];
for (AggregateResult res : primary) {
Id acId = (Id)res.get('acID');
Account ac = accounts.get(acId);
switch on level {
when 'Primary' {
ac.Primary_Contacts__c = (Integer)res.get('TOTAL');
}
when 'Secondary' {
ac.Secondary_Contacts__c = (Integer)res.get('TOTAL');
}
when 'Tertiary' {
ac.Tertiary_Contacts__c = (Integer)res.get('TOTAL');
}
}
}
}
update accounts.values();
}
}
By Esra Balci
public class AggregateResultForAccount {
public static void updateAccountCounts() {
Map<Id, Account> accountsMap = new Map<Id, Account>([SELECT Id FROM Account WHERE Id IN (SELECT AccountId FROM Contact)]);
List<AggregateResult> contactCounts = [ SELECT AccountId conAccID, Level__c, COUNT(Id) TOTAL
FROM Contact
WHERE Level__c IN (‘Primary’, ‘Secondary’, ‘Tertiary’)
GROUP BY AccountId, Level__c];
for (AggregateResult each : contactCounts) {
Id conAccID = (Id)each.get(‘conAccID’);
Account acc = accountsMap.get(conAccID);
Integer count = (Integer)each.get(‘TOTAL’);
String contactLevels = (String)each.get(‘Level__c’);
switch on contactLevels {
when ‘Primary’{
acc.Primary_Contacts__c = count;
}
when ‘Secondary’{
acc.Secondary_Contacts__c = count;
}
when ‘Tertiary’{
acc.Tertiary_Contacts__c = count;
}
}
}
update accountsMap.values();
}
}
Video
Video does not exists.