1 year ago
#189682
Abhijith Poojary
Restrict more then 2 contacts that saved on Account object
I want to build a trigger on contact, that accept check box. And In Account object it take 2 contacts that are active. when user assign 3rd active contact to the same account he/she will get error messege. how can it possible? i completed all codes but these limit of 2 contacts are pending. can anyone try to guide me how to do this?
trigger ContactTrigger on Contact(after insert, after update, after delete, after undelete) {
switch on Trigger.operationType {
when AFTER_INSERT {
Set<Id> accountIds = new Set<Id>();
for (Contact con : Trigger.new) {
if (String.isNotBlank(con.AccountId)) {
//write automation logic here
accountIds.add(con.AccountId);
}
}
// get aggregate result for all accounts
List<AggregateResult> results = [
SELECT AccountId, COUNT(Id) totalContacts
FROM Contact
WHERE Active__c = TRUE AND AccountId IN :accountIds
GROUP BY AccountId
];
integer var = results.size();
// build final list of accounts to update
List<Account> accountsToUpdate = new List<Account>();
for (AggregateResult result : results) {
// get account id and number of active contacts
String accId = String.valueOf(result.get('AccountId'));
Integer totalContacts = Integer.valueOf(result.get('totalContacts'));
// make sure you use Id feild in your account to update it
Account acc = new Account(Id = accId, Active_Contacts__c = totalContacts);
accountsToUpdate.add(acc);
}
// update the final list of account
update accountsToUpdate;
}
when AFTER_UPDATE {
Set<Id> accountIds = new Set<Id>();
for (Contact con : Trigger.new) {
// capture the account id only if active checkbox value is flipped
if (String.isNotBlank(con.AccountId) && Trigger.oldMap.get(con.Id).Active__c != con.Active__c) {
// write automation logic here
accountIds.add(con.AccountId);
} else if (Trigger.oldMap.get(con.Id).AccountId != con.AccountId) {
accountIds.add(con.AccountId);
accountIds.add(Trigger.oldMap.get(con.Id).AccountId);
}
}
// get aggregate result for all accounts
List<AggregateResult> results = [
SELECT AccountId, COUNT(Id) totalContacts
FROM Contact
WHERE Active__c = TRUE AND AccountId IN :accountIds
GROUP BY AccountId
];
// build final list of accounts to update
List<Account> accountsToUpdate = new List<Account>();
for (AggregateResult result : results) {
// get account id and number of active contacts
String accId = String.valueOf(result.get('AccountId'));
Integer totalContacts = Integer.valueOf(result.get('totalContacts'));
// make sure you use Id feild in your account to update it
Account acc = new Account(Id = accId, Active_Contacts__c = totalContacts);
accountsToUpdate.add(acc);
}
// update the final list of account
update accountsToUpdate;
}
}
}
salesforce
apex
apex-trigger
salesforce-development
0 Answers
Your Answer