Showing posts with label count. Show all posts
Showing posts with label count. Show all posts

Friday, February 19, 2021

How to count numberofcontacts trigger

To Count numberofcontacts using trigger.We can use RollupSummary for master-detail  relationship,but we  can create  

only 2 master-detail  reationships  for an  object.

1.we  have  to  create  a read-only field with  number to get count

2.we should create read-only field  in parent object.

3.we  have  to get count from  the child  object,so   we  write   trigger only  child object.

Note:If any queries please comment.

trigger NumberofContacts on contact(after insert,after update,after delete)

{

map<id,integer> mapacc=new map<id,integer>();

list<Account> 1stacc=new list<Account>();

if(trigger.isInsert)

{

for(contact con:trigger.new)

{

integer count=0;

if(mapacc.containskey(con.Accountid))

{

count+=mapacc.get(con.accountid);

}

count++;

mapacc.put(con.Accountid,count);

}

if(!mapacc.isempty())

{

for(Account acc:[select id,name,numberofcontacts__c from Account where id in:mapacc.keyset()])

{

Account a:new Account(id=acc.id);

mapacc.containskey(acc.id);

if(a.numberofcontacts__c!=null)

{

a.numbeeofcontacts__c=acc.numberofcontacts__c+mapacc.get(acc.id);

}

else

{

a.numberofcontacts__c=mapacc.get(acc.id);

}

firstacc.add(a);

}

}

}

if(trigger.isUpdate)

{

for(contact con:trigger.new)

{

integer count=0;

if(mapacc.containskey(con.Accountid))

{

count+=mapacc.get(con.accountid);

}

count++;

mapacc.put(con.Accountid,count);

}

for(contact con:trigger.old)

{

integer count=0;

if(mapacc.containskey(con.Accountid))

{

count+=mapacc.get(con.accountid);

}

count--;

mapacc.put(con.Accountid,count);

}

if(!mapacc.isempty())

{

for(Account acc:[select id,name,numberofcontacts__c from Account where id in:mapacc.keyset()])

{

Account a:new Account(id=acc.id);

mapacc.containskey(acc.id);

if(a.numberofcontacts__c!=null)

{

a.numbeeofcontacts__c=acc.numberofcontacts__c+mapacc.get(acc.id);

}

else

{

a.numberofcontacts__c=mapacc.get(acc.id);

}

firstacc.add(a);

}

}

}

if(trigger.isDelete)

{

for(contact con:trigger.old)

{

integer count=0;

if(mapacc.containskey(con.Accountid))

{

count+=mapacc.get(con.accountid);

}

count--;

mapacc.put(con.Accountid,count);

}

if(!mapacc.isempty())

{

for(Account acc:[select id,name,numberofcontacts__c from Account where id in:mapacc.keyset()])

{

Account a:new Account(id=acc.id);

mapacc.containskey(acc.id);

if(a.numberofcontacts__c!=null)

{

a.numbeeofcontacts__c=acc.numberofcontacts__c+mapacc.get(acc.id);

}

else

{

a.numberofcontacts__c=mapacc.get(acc.id);

}

firstacc.add(a);

}

}

}

if(!firstacc.isempty())

           {

               update firstacc;

           }


}


Automatically Covert a lead to Account,contact,Opportunity Trigger.

 How   to   convert    Automatically  lead to Account,contact,Opportunity   Trigger. trigger LeadHandler on Lead (after insert) {     list...