trigger to block more than 2 contacts per account. This trigger is working fine on after insert.
But I have confusion that it should be on before insert as we want this trigger to work before inserting account but on after insert this trigger is not working fine as even 100 contacts are getting created of a account by writing script.
trigger BlockMoreThan2ContactOnAccount on Contact (after insert, after update, after undelete) {
Set<Id> accountIds = new Set<Id>();
for(Contact record: Trigger.new) {
accountIds.add(record.AccountId);
}
accountIds.remove(null);
Set<Id> morethan2Contacts = new Map<Id, AggregateResult>([
SELECT AccountId Id
FROM Contact
WHERE AccountId = :accountIds
GROUP BY AccountId
HAVING COUNT(Id) > 2]).keySet();
for(Contact record: Trigger.new) {
if(moreThan2Contacts.contains(record.AccountId)) {
record.AccountId.addError('You may not have more than 2 contacts per account.');
}
}
Plz check it once.. When this trigger is on before insert.. 3.4.5 n no of contacts are getting created by writing script
account acc=new account(); acc.name='df';
insert acc;
list con=new list(); for(integer i=0;i<3;i++) { contact c=new contact(); c.lastname='sd'; c.accountid=acc.id; con .add(c); } insert con
;
On before this script is working and contacts are getting created.. But on after insert contacts are not getting created. Can anyone clear the doubt