You are on page 1of 2

/* Q2.

Create a trigger to validate that no more than 3 contact get added to an


account. */

trigger LimitOfContactOnAcc on Contact (before insert, before update, after


undelete) {
Set<Id> accIds=new Set<Id>();
if(trigger.isBefore && (trigger.isInsert || trigger.isUpdate)) {
if(trigger.isBefore && trigger.isInsert)
{
for(Contact con:trigger.new)
{
if(con.AccountId <> null)
{
accIds.add(con.AccountId);
}
}
}
else if(trigger.isBefore && trigger.isUpdate)
{
for(Contact con:trigger.new)
{
if(con.AccountId <> null){
Contact oldMapValue=trigger.oldMap.get(con.Id);
if(oldMapValue.AccountId !=con.AccountId)
{
accIds.add(con.AccountId);
}
}
}
}
Set<Id> accListWithCon = new Map<Id, AggregateResult>([SELECT AccountId Id
FROM Contact WHERE AccountId = :accIds GROUP BY AccountId HAVING COUNT(Id)
>=3]).keySet();
if(accListWithCon.size()>0){
for(Contact newCon: Trigger.new) {
if(newCon.AccountId <> null &&
accListWithCon.contains(newCon.AccountId)) {
newCon.addError('SORRY!! You can not insert more than 3
contacts on Account.');
}
}
}
}

if(trigger.isAfter && trigger.isUndelete)


{
for(Contact con:trigger.new)
{
if(con.AccountId <> null)
{
accIds.add(con.AccountId);
}
}
Set<Id> accListWithCon = new Map<Id, AggregateResult>([SELECT AccountId Id
FROM Contact WHERE AccountId = :accIds GROUP BY AccountId HAVING COUNT(Id) >
3]).keySet();
if(accListWithCon.size()>0){
for(Contact newCon: Trigger.new) {
if(newCon.AccountId <> null &&
accListWithCon.contains(newCon.AccountId)) {
newCon.addError('SORRY!! You can not insert more than 3
contacts on Account.');
}
}
}
}
}

// using after event trigger

/* Q2.Create a trigger to validate that no more than 3 contact get added to an


account. */

trigger LimitOfContactOnAcc on Contact (after insert, before Insert, before update,


after update, after undelete) {
Set<Id> accIds = new Set<Id>();
if (Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate ||
Trigger.isUndelete)){
for(Contact con:trigger.new)
{
if(con.AccountId <> null)
{
accIds.add(con.AccountId);
}
}
Set<Id> accListWithCon = new Map<Id, AggregateResult>([SELECT AccountId Id
FROM Contact WHERE AccountId = :accIds GROUP BY AccountId HAVING COUNT(Id) >
3]).keySet();
if(accListWithCon.size()>0){
for(Contact newCon: Trigger.new) {
if(newCon.AccountId <> null &&
accListWithCon.contains(newCon.AccountId)) {
newCon.addError('SORRY!! You can not insert more than 3
contacts on Account.');
}
}
}
}
}

You might also like