onContactAddTotalNumOfConAtAccLabel
trigger onContactAddTotalNumOfConAtAccLabel on Contact (after delete, after insert)
{
List<Account> lstacc=new List<Account>();
set<ID> accid= new Set<Id>();
list<Account> lstAccountToUpdate = new list<Account>();
if(trigger.isInsert && trigger.IsAfter)
{
for(Contact con:trigger.new)
{
accid.add(con.AccountID);
}
lstacc= [Select ID, TotalContact__c from Account where ID In: accid];
if(lstacc.size()>0)
{
for(Account accObj:lstacc)
{
for(Contact conObj:trigger.new)
{
if(accObj.ID==conObj.AccountID)
{
Integer i=0;
if(accObj.TotalContact__C!=null)
{
i=Integer.valueOf(accObj.TotalContact__C);
accObj.TotalContact__C=i+1;
}
else
{
accObj.TotalContact__C=i+1;
}
}
}
lstAccountToUpdate.add(accObj);
}
}
}
if(trigger.isDelete && trigger.IsAfter)
{
for(Contact con:trigger.old)
{
accid.add(con.AccountID);
}
lstacc= [Select ID, TotalContact__c from Account where ID In: accid];
if(lstacc.size()>0)
{
for(Account accObj:lstacc)
{
for(Contact conObj1:trigger.old)
{
if(accObj.ID==conObj1.AccountID)
{
Integer i=0;
if(accObj.TotalContact__C!=null)
{
i=Integer.valueOf(accObj.TotalContact__C);
accObj.TotalContact__C=i-1;
}
else
{
accObj.TotalContact__C=i-1;
}
}
}
lstAccountToUpdate.add(accObj);
}
}
}
if(lstAccountToUpdate.size()>0)
{
update lstAccountToUpdate;
}
}
{
List<Account> lstacc=new List<Account>();
set<ID> accid= new Set<Id>();
list<Account> lstAccountToUpdate = new list<Account>();
if(trigger.isInsert && trigger.IsAfter)
{
for(Contact con:trigger.new)
{
accid.add(con.AccountID);
}
lstacc= [Select ID, TotalContact__c from Account where ID In: accid];
if(lstacc.size()>0)
{
for(Account accObj:lstacc)
{
for(Contact conObj:trigger.new)
{
if(accObj.ID==conObj.AccountID)
{
Integer i=0;
if(accObj.TotalContact__C!=null)
{
i=Integer.valueOf(accObj.TotalContact__C);
accObj.TotalContact__C=i+1;
}
else
{
accObj.TotalContact__C=i+1;
}
}
}
lstAccountToUpdate.add(accObj);
}
}
}
if(trigger.isDelete && trigger.IsAfter)
{
for(Contact con:trigger.old)
{
accid.add(con.AccountID);
}
lstacc= [Select ID, TotalContact__c from Account where ID In: accid];
if(lstacc.size()>0)
{
for(Account accObj:lstacc)
{
for(Contact conObj1:trigger.old)
{
if(accObj.ID==conObj1.AccountID)
{
Integer i=0;
if(accObj.TotalContact__C!=null)
{
i=Integer.valueOf(accObj.TotalContact__C);
accObj.TotalContact__C=i-1;
}
else
{
accObj.TotalContact__C=i-1;
}
}
}
lstAccountToUpdate.add(accObj);
}
}
}
if(lstAccountToUpdate.size()>0)
{
update lstAccountToUpdate;
}
}
Comments
Post a Comment