+ Start a Discussion
srikanth j 24srikanth j 24 

Apex Triggers in Salesforce

Hi Guys
i am new to coding 
What is meant by triggers and context variables?
I had a scenario i.e.i need to display Account Related Contacts using trigger can anyone help me out
Advance Thanks
 
ManojjenaManojjena
Hi srikanth ,

need to display Account Related Contacts using trigger  .I am not getting your question .We can not displsy any thing through trigger .
To know the basic concept you can go through the below link .

http://manojjena20.blogspot.in/2013/03/manojs-trigger-blog.html  . (http://manojjena20.blogspot.in/2013/03/manojs-trigger-blog.html  .)

Also you can check links like trial head which Karthik has shared .

If you need help please explain your requirment clearly so that I will help !!
Thanks 
Manoj

 
srikanth j 24srikanth j 24
Sorry for the mistake My Question is Triiger to count number of contacts associated with Account?
ManojjenaManojjena
Hi Srikanth ,

try with below code it will help !!
trigger ContactCount  on Contact ( after insert,after delete,after undelete) {
     Set<Id> accIdSet=new Set<Id>();
     List<Account> accListToUpdate=new List<Account>();
    if(Trigger.isInsert || Trigger.isUndelete){
        for(Contact con : Trigger.new){
            if(con.AccountId != null)
                accIdSet.add(con.AccountId);     
        }
    }If(Trigger.isDelete){
       for(Contact con  : Trigger.old){
            if(con.AccountId != null)
                accIdSet.add(con.AccountId);     
        }
    }
   for(AggregateResult res : [SELECT count(Id)can,AccountId FROM Contact WHERE AccountId IN :accIdSet group by AccountId]) {
          accListToUpdate.add(new Account(Id=(Id)res.get('AccountId'),Contact_Count__c=(Integer)res.get('can')));
    }
    try{
      update accListToUpdate;
    }catch(DmlException de){
      System.debug(de);
    }
}
Replace Contact_Count__c field with field Api in Account .
Let me know if it helps !!!
Thanks 
Manoj
 
Akshit HuriaAkshit Huria
trigger NOC on Contact (after insert, after delete, after update, after undelete) 
{
    set<Id> accid=new set<Id>();
    if(trigger.isInsert || trigger.isUpdate || trigger.isUndelete)
    {
        for(Contact con:trigger.new)
        {
            accid.add(con.AccountId);
        }
    }
    if(trigger.isDelete)
    {
        for(Contact con:trigger.old)
        {
            accid.add(con.AccountId);
        }
    }
    List<Account> lstacc=[select id, noc__c, (select id from contacts) from Account where id in:accid ];
    for(Account acc:lstacc)
    {
        acc.noc__c=acc.contacts.size();
    }
    System.debug(lstacc);
    update lstacc;
}
Mark this as solved if your query get resolved
Akshit