Wednesday, July 5, 2017

TRigger scenario 7 in salesforce :

Duplicate Name:
trigger duplicateAccName on Account (before insert,before update) {               /* for(account acc :trigger.new){         if(trigger.newmap.get(acc.id).name == trigger.oldmap.get(acc.id).name){             acc.name.adderror('You cannot create a dulplicate account......');                     }     }         */     list<string> accnames = new list<string>();     for(account acc : trigger.new){         accnames.add(acc.name);     }     list<account> acclst = [select id,name from account where name IN: accnames];     for(account acc1 : trigger.new){         if(acclst.size()>0){                 acc1.name.adderror('You cannot create a dulplicate account');          
   }         } }
-----------------------------------------------------------------
trigger triggername on Account (before update,before insert) {

    Map<string,Account> accMap = new Map<string,Account>();
    set<string> accSet = new set<string>();
    for(Account acc : Trigger.new){
        accSet.add(acc.name);
    }
    for(Account a : [select id,name from Account where name in : accSet]){
        accMap.put(a.name,a);
    }
    for(Account acc1 : trigger.new)
        {
         if(accMap.containskey(acc1.name)){
           if(Trigger.isInsert){
             acc1.name.addError('Account name Already Exist For Insert!');
           }
           else if(Trigger.isUpdate){
             acc1.name.addError('Account name Already Exist For Update!!'); 
           }
            }
        }
    
    /* for(account a : trigger.new){
      //  a.accountnumber = a.site;
        if(trigger.oldmap.get(a.id).name == trigger.newmap.get(a.id).name){
            a.name.adderror('Duplicate name');
        }
        
    }  */

}
------------------------------------------------------------------
Scenario:Create 'sales rep' text field in account object when we create the account 
record,the account owner will be automatically added to sales rep field.when we update the 
account owner of the record then also the sales rep will be automatically updated.
trigger AcctoconTrigger on Account (before insert ,before update) {
    map<id,account> mapusr = new map<id,account>();
    if(trigger.isbefore && (trigger.isupdate || trigger.isinsert)){
        for(account acc : trigger.new){
            mapusr.put(acc.OwnerId,acc);
        }
        map<id,user> mapusr1 = new map<id,user>([select id,name from user where id IN:mapusr.keyset()]);
        for(account acc : trigger.new){
            acc.sales_rep__c = mapusr1.get(acc.OwnerId).name;
        }
    }
}

Trigger Scenario 6 In salesforce ROLLUP SUMMARY for COUNT:

//Trigger Best practice for count

trigger CountContacts on contact (after delete,after update, after insert, after undelete) {
 list<account> lstacc = new list<account>();
set<id> accids = new set<id>();
if(trigger.isInsert && trigger.isafter){
  for(contact con : Trigger.new){
      accids.add(con.accountid);
   }
}
else if(trigger.isDelete && trigger.isafter){
    for(contact con : Trigger.old){
        accids.add(con.accountid);
     }
}
else if(trigger.isUnDelete && trigger.isafter){
     for(contact con : Trigger.new){
     accids.add(con.accountid);
      }
}
else if(trigger.isUpdate && trigger.isafter){
     for(contact con : trigger.new){
if(trigger.oldmap.get(con.id).accountid!=con.accountid){
accids.add(con.accountid);
accids.add(trigger.oldmap.get(con.id).accountid);
}
}
}
AggregateResult[] groupedResults = [SELECT COUNT(Id), accountid FROM contact where accountid IN :accids GROUP BY accountid ];
   for(AggregateResult ar:groupedResults) {
        Id custid = (ID)ar.get('accountid');
        Integer count = (INTEGER)ar.get('expr0');
        account cust1 = new account(Id=custid);
        cust1.NumberofLocations__c = count;
        lstacc.add(cust1);
     }
     update lstacc;
}
-------------------------------------------------------------------
Trigger Scenario for Sum of Amount of all child to parent


trigger TestingContactTrigger on Contact (before update,after insert,after update,after delete,after undelete) {
    list<account> lstacc = new list<account>();
    set<id> ids = new set<id>();
    if(Trigger.isafter && (trigger.isinsert || trigger.isupdate || trigger.isundelete)){
        for(contact con : trigger.new){
            ids.add(con.accountid);
        }
    }
    if(trigger.isafter && trigger.isdelete){
        for(contact con : trigger.old){
            ids.add(con.AccountId);
        }
    }
    list<aggregateresult> lstagr =[Select SUM(Amount__c) totalSum, accountid From contact Where accountid IN : Ids GROUP BY accountid];
    for(aggregateresult ag : lstagr){
        id accid = (ID)ag.get('accountid');
        double amount = (DOUBLE)ag.get('totalsum');
        account acc = new account(id = accid);
        acc.Total__c = amount;
        lstacc.add(acc);
    }
    update lstacc;
}

-------------------------------------------------------------------

---------------------------------------------------------------------Another way-----
Trigger triggername on contact(after insert,after update,after delete,after undelete){
Set<id> accids = new set<id>();
    map<id,list<contact>> mapcon = new map<id,list<contact>>();
    if(trigger.isafter &&(trigger.isinsert ||trigger.isupdate || trigger.isundelete)){
        for(contact con : trigger.new){
            accids.add(con.AccountId);
        }
    }
    if(trigger.isafter && trigger.isdelete){
        for(contact con : trigger.old){
            accids.add(con.AccountId);
        }
    }
 
 
  //  list<contact> lstcon = [select id,lastname,amount1__c,accountid from contact where accountid IN: accids];
    //   integer count = lstcon.size();
     
    list<account> lstacc = new list<account>();
    for(account acc :[select id,name,NumberofLocations__c,(select id from contacts)from account where id IN:accids]){
       acc.NumberofLocations__c = acc.contacts.size();
        lstacc.add(acc);
    }
    update lstacc;
}
----------------------------------------------------
Rollup summary Amount

trigger RollupOppAmountTrigger on Opportunity (after insert,after update,after delete,after undelete) {
       Map<Id, List<Opportunity>> acctIdOpptyListMap = new Map<Id, List<Opportunity>>();
       Set<string> acctIds = new Set<string>();
    if(trigger.isUpdate || trigger.isInsert || trigger.isundelete){
        for(Opportunity oppty : trigger.New){
                acctIds.add(oppty.AccountId);
        }  
    }
    if(trigger.isDelete){
        for(Opportunity oppty : trigger.old){
              acctIds.add(oppty.AccountId);
        }  
    }
    if(acctIds.size() > 0){
        for(Opportunity oppty : [SELECT Amount, AccountId FROM Opportunity WHERE AccountId IN : acctIds]){
            if(!acctIdOpptyListMap.containsKey(oppty.AccountId)){
                acctIdOpptyListMap.put(oppty.AccountId, new List<Opportunity>());
            }
            acctIdOpptyListMap.get(oppty.AccountId).add(oppty);
        }
        List<Account> acctList = new List<Account>();
        for(Account acct : [SELECT NumberofLocations__c  FROM Account WHERE Id IN: acctIds]){
            List<Opportunity> tempOpptyList = new List<Opportunity>();
            tempOpptyList = acctIdOpptyListMap.get(acct.Id);
            Double totalOpptyAmount = 0;
            for(Opportunity oppty : tempOpptyList){
                if(oppty.Amount != null){
                    totalOpptyAmount += oppty.Amount;
                }
            }
            acct.NumberofLocations__c  = totalOpptyAmount;
           acctList.add(acct);
        }
        update acctList;
    }
}

Trigger Scenario 5 In salesforce Names:


Trigger triggername on contact(after insert ,after update,after delete,after undelete) 
Set<id> accids = new set<id>();
    map<id,string> mapcon = new map<id,string>();
    if(trigger.isafter &&(trigger.isinsert ||trigger.isupdate || trigger.isundelete)){
        for(contact con : trigger.new){
            accids.add(con.AccountId);
        }
    }
    if(trigger.isafter && trigger.isdelete){
        for(contact con : trigger.old){
            accids.add(con.AccountId);
        }
    }
    for(contact con : [select id,lastname,accountid from contact where accountid IN: accids]){
        if(mapcon.containsKey(con.accountid)){
           mapcon.put(con.accountid,mapcon.get(con.AccountId) +','+con.LastName); 
        }
        else{
            mapcon.put(con.AccountId,con.LastName);
        }
    }
    list<account> lstacc = new list<account>();
    for(account acc :[select id,name,All_ASN_providers__c from account where id IN: mapcon.keySet()]){
        acc.All_ASN_providers__c = mapcon.get(acc.id);
      lstacc.add(acc);
    }
    update lstacc;
}

---------------------------------------
Trigger:
trigger RollupFutureTrigger on Contact (after insert,after update ,after delete,after undelete) {
  set<id> accids = new set<id>();
    if(trigger.isafter &&(trigger.isinsert ||trigger.isupdate||trigger.isundelete)){
        for(contact con :trigger.new){
            accids.add(con.accountid);
        }
    }
    if(trigger.isafter && trigger.isdelete){
        for(contact con : trigger.old){
            accids.add(con.accountid);
        }
    }
    RollupFutureCLS.countContacts(accids);
    RollupFutureCLS.AddnameofContacts(accids);
}
----------
Class:
Global class RollupFutureCLS {
 @future
  global static void countContacts(set<id> setId)
  {
      List<Account> lstAccount = [select id,NumberOfEmployees, (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
      {
         acc.NumberOfEmployees = acc.contacts.size();
       }
      update lstaccount;
  }
    @future
    global static void AddnameofContacts(set<id> setId)
  {
      list<account> lstaccount = new list<account>();
      map<id,string> mapacc = new map<id,string>();
      for(contact con : [select id,lastname,email,accountid from contact where accountid=:setId]){
         if(mapacc.containsKey(con.accountid) ||test.isRunningTest()){
          mapacc.put(con.accountid,mapacc.get(con.accountid)+','+con.lastname);
      }
          else{
              mapacc.put(con.accountid,con.lastname);
          }
      }
     
      for( Account acc : [select id,name,email__c,Z_Grandfather_for__c from account where id=:mapacc.keySet()] )
      {
         acc.Z_Grandfather_for__c = mapacc.get(acc.id);
          lstaccount.add(acc);
       }
      update lstaccount;
  }
}
--------
Test Class:
@IsTest
public class RollupFutureCLS_Test {
    public static testmethod void TestRollupFutureMetod()
    {
        Account a = new Account();
        a.Name = 'Test Account';
        Insert a;

        Contact cont = New Contact();
        cont.FirstName ='Bob';
        cont.LastName ='Masters';
        cont.AccountId = a.Id;
        cont.Phone ='9916767632';
        cont.Email ='test@gmail.com';
        Insert cont;
       
        set<Id> setAccId = new Set<ID>();
        setAccId.add(a.id);

        Test.startTest();
            RollupFutureCLS.countContacts(setAccId);
        RollupFutureCLS.AddnameofContacts(setAccId);
        Test.stopTest();
       
        Account ACC = [select NumberOfEmployees from Account where id = :a.id LIMIT 1];
        System.assertEquals ( Integer.valueOf(ACC.NumberOfEmployees) ,1);
  }
 
}

Trigger Scenario 4 in salesforce: Parent to child


-------------------------------
trigger BestPracticesforaccountandcon on account (after insert,after update) 
{
list<contact> lstcon = new list<contact>();
if(trigger.isafter && trigger.isinsert){
    for(account acc : trigger.new){
    contact con = new contact();
    con.lastname = acc.name;
    con.accountid = acc.id;
    con.email = acc.email__c;
    lstcon.add(con);
    
    }
    insert lstcon;
    }
if(trigger.isafter && trigger.isupdate){    
    for(contact con :[select id,lastname,email,accountid from contact where accountid in :trigger.newmap.keyset()]){
       con.accountid = trigger.newmap.get(con.accountid).id;
        con.lastname = trigger.newmap.get(con.accountid).name;
        con.email = trigger.newmap.get(con.accountid).email__c;
        lstcon.add(con);
    }
    }
update lstcon;
-------------------------------
Note :trigger UpdateActiveProspect1 on Opportunity (before update) {
           (or)

trigger UpdateActiveProspect1 on Opportunity (after insert,after update) {

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

   set<id> accids = new set<id>();

    list<account> updatelstacc = new list<account>();

    for(Opportunity opp : trigger.new){

      //  accids.add(opp.accountid);
        mapacc.put(opp.AccountId, opp);
           }
 //   for(account acc : [select id,name from account where id IN:accids]){

for(account acc : [select id,name from account where id IN :mapacc.keyset()]){
        if(mapacc.containsKey(acc.id)){
            if(mapacc.get(acc.id).stageName=='Qualification'||mapacc.get(acc.id).stageName=='Needs Analysis'||
 mapacc.get(acc.id).stageName=='Value Proposition'||mapacc.get(acc.id).stageName=='Proposal/Price Quote'||
                 mapacc.get(acc.id).stageName=='Id. Decision Makers'||mapacc.get(acc.id).stageName=='Perception Analysis'||
               mapacc.get(acc.id).stageName=='Negotiation/Review'){
                acc.Active_Prospect__c = true;
                 acc.Email__c = mapacc.get(acc.id).email__c;
            }else{
                acc.Active_Prospect__c = false;
                 acc.Email__c = mapacc.get(acc.id).email__c;
            }
            updatelstacc.add(acc);
        }
    }
  update updatelstacc;
}
--------------------------------------------------------------------------
Parent to Child:
trigger AcctoconTrigger on Account (before update,before delete) {
    if(trigger.isbefore && trigger.isupdate){
    list<contact> lstcon = new list<contact>();
    for(contact con : [select id,lastname,accountid,email from contact where accountid IN: trigger.newmap.keyset()]){
        if(trigger.newmap.containsKey(con.AccountId)){
            con.Email = trigger.newmap.get(con.AccountId).email__c;
            lstcon.add(con);
        }
    }
    if(lstcon.size()>0 || lstcon.size() != null){
        update lstcon;
    }
    }
    if(trigger.isbefore && trigger.isdelete){
     list<contact> lstcon1 = [select id,lastname,email from contact where accountid IN:trigger.oldmap.keyset()];
        delete lstcon1;
    }
------------------------------------------------------------------------

trigger AcctoconTrigger on Account (before update) {
    list<contact> lstcon = new list<contact>();

    for(contact con : [select id,lastname,accountid,email from contact where accountid IN :trigger.newmap.keyset()]){
    if(trigger.newmap.containsKey(con.AccountId)){
    con.Email =trigger.newmap.get(con.accountid).email__c;

            lstcon.add(con);
        }
    }
    if(lstcon.size()>0 || lstcon.size() != null){
        update lstcon;
    }
}
------------------------------------------------------------------------------
Child to Parent:

trigger childtoparent on Contact (before update) {
    list<account> lstacc = new list<account>();
    map<id,contact> mapcon = new map<id,contact>();
    for(contact con : trigger.new){
        mapcon.put(con.AccountId,con);
    }
    for(account acc :[select id,name,email__c from account where id IN:mapcon.keyset()]){
        acc.Email__c = mapcon.get(acc.Id).email;
        lstacc.add(acc);
    }
    if(lstacc.size()>0 || lstacc.size() != null){
        update lstacc;
    }
----------------------------------
Write like below :
trigger childtoparent on Contact (after update,after insert) {
    list<account> lstacc = new list<account>();
    for(contact con : trigger.new){
        if(con.RMA_Shipping_Contact_Only__c == true){
        account acc = new account(name = con.lastname,id = con.AccountId,email__c = con.Email);
        lstacc.add(acc);
    }
    }
    update lstacc;

}

When we run below code from Developer console get the error like:

list<contact> lstcon = new list<contact>();
contact con = new contact(lastname ='venkat',phone = '9916767632',email ='test@gmail.com',accountid='0012800001S1LTZ',RMA_Shipping_Contact_Only__c =true);
contact con1 = new contact(lastname ='venkat1',phone = '9916767632',email ='test1@gmail.com',accountid='0012800001S1LTZ',RMA_Shipping_Contact_Only__c =true);
lstcon.add(con);
lstcon.add(con1);
insert lstcon;

Error:
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, childtoparent: execution of AfterInsert caused by: System.ListException: Duplicate id in list: 0012800001S1LTZAA3 Trigger.childtoparent: line 9, column 1: []

Trigger scenario 3 in Salesforce:

Using Trigger to populate the account type on the contact record
trigger triggername on contact(before update,before insert){
     if(trigger.isbefore && (trigger.isupdate|| trigger.isinsert){
    Set<Id> accountIds = new Set<Id>();
         for(contact ct: Trigger.new){
       accountIds.add(ct.id);
         }
if(!accids.isempty()){
 map<id,account> mapacc = new map<id,account>([select id,name ,type from account where id IN: accountids]);
for(contact con : trigger.new){
  if(con.accountid != null){
    con.acctype__c = mapacc.get(con.accountid).type;
}
}
}

Trigger to update parent object value with child value and recursive trigger and updating same parent object not child object:

Note:below trigger it doesn't work in this trigger.

trigger AcctoOppTrigger on Account (after update) {
 list<account> lstacc1 = new list<account>();
     if(trigger.isafter && trigger.isupdate){
    Set<Id> accountIds = new Set<Id>();
         for(Account ct: Trigger.new){
       accountIds.add(ct.id);
         }
     list<account> lstacc =  [select id,name,email__c,(select id,email, lastname, Level__c,accountid from contacts where Level__c ='primary') from account where id in : accountIds];
   for(Account ct: lstacc){
       for(contact con : ct.contacts){
           ct.Email__c = con.Email;
             lstacc1.add(ct);
       }
   }
       //  if(recusrssionPreventController.flag == true){
       //    recusrssionPreventController.flag = false;
             if(lstacc1.size()>0)
              update lstacc1;
      // }
     }
}
Note:
With out this below lines it should get below error:
 if(recusrssionPreventController.flag == true){
          recusrssionPreventController.flag = false;
             if(lstacc1.size()>0)
              update lstacc1;
       }
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger AcctoOppTrigger caused an unexpected exception, contact your administrator: AcctoOppTrigger: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0012800000exmUvAAI; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AcctoOppTrigger: maximum trigger depth exceeded Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv] Account trigger event AfterUpdate for [0012800000exmUv]: []: Trigger.AcctoOppTrigger: line 18, column 1

Note:
If filed value 'level__c'is 'primary' have in 2 contact records associated parent it will one more error like below: 
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger AcctoOppTrigger caused an unexpected exception, contact your administrator: AcctoOppTrigger: execution of AfterUpdate caused by: System.ListException: Duplicate id in list: 0012800000exmUvAAI: Trigger.AcctoOppTrigger: line 18, column 1


------------------------------------------------------------------------------------------------
trigger BestPracticesforaccountandcon on account (after insert,after update) 
{
    
  
  //This queries all Contacts related to the incoming Account records in a single SOQL query.
  //This is also an example of how to use child relationships in SOQL
  List<Account> accountsWithContacts = [select id, name,email__c, (select id, salutation, description, 
                                                                firstname, lastname, email from Contacts) 
                                                                from Account where Id IN :Trigger.newMap.keySet()];
  
  List<Contact> contactsToUpdate = new List<Contact>{};
  // For loop to iterate through all the queried Account records 
  for(Account a: accountsWithContacts){
     // Use the child relationships dot syntax to access the related Contacts
     for(Contact c: a.Contacts){
      System.debug('Contact Id[' + c.Id + '], FirstName[' + c.firstname + '], LastName[' + c.lastname +']');
      c.Description=c.salutation + ' ' + c.firstName + ' ' + c.lastname;
         c.Email = a.email__c;
      contactsToUpdate.add(c);
     }      
   }
      
   //Now outside the FOR Loop, perform a single Update DML statement. 
   update contactsToUpdate;

  /*  if(Trigger.isafter)
    {
        list<contact> allcontacts = new list<contact>();
        if(trigger.isinsert)
        {
            for(integer i = 0;i<Trigger.new.size();i++)
            {
                contact con = new contact();
                con .LastName= Trigger.new[i].name;
              // con .LastName =con .LastName + 'devi';
                con .Email= Trigger.new[i].Email__c;
                con .Department= Trigger.new[i].AccountNumber;
                con .Accountid = Trigger.new[i].id;
                allcontacts.add(con);
             } 
               insert allcontacts;
          }
        
        list<id> allAccountIDs = new list<id>();
        map<id,account> allAccounts = new Map<id,account>();
        if(Trigger.isupdate)
        {
                for(integer i = 0;i<Trigger.new.size();i++)
           {
               allAccountIDs.add(Trigger.new[i].id);
               allAccounts.put(Trigger.new[i].id,Trigger.new[i]);
            }
            list<contact> listcon = [select id,LastName,Email,Department,AccountID  from contact where Accountid =:allAccountIDs];    
            for(integer i =0;i<listcon.size();i++)
            {
                if(allAccounts.containskey(listcon[i].AccountID ))
                {
                     // listcon[i].LastName =listcon[i].LastName+'devi';
                    listcon[i].LastName = allAccounts.get(listcon[i].AccountID ).name;
                    listcon[i].Email = allAccounts.get(listcon[i].AccountID ).Email__c;
                    listcon[i].phone = allAccounts.get(listcon[i].AccountID ).phone;
                    listcon[i].Department = allAccounts.get(listcon[i].AccountID ).AccountNumber;
                    listcon[i].Accountid = allAccounts.get(listcon[i].AccountID).id;
                    allcontacts.add(listcon[i]);
                }
            }
                 update allcontacts;
        }    
    } */

}

Trigger scenario2 in salesforce :

Account - Account Number -india
countrty__c - name(Text) and Checkbox__c  --
insert contact. 

While inserting Account field account number value is 'India' then compare to without related object Country__c ,and have field name value 'India' and  
Checkbox__c  ='true'
Then insert the contact. If doesn't have 
field name value 'India' and  Checkbox__c  ='true' doesn't insert the contact.

Trigger triggernameForPorton on account(after insert){
   list<contact> lstcon = new list<contact>();
   set<string> sbc = new set<string>();
   Map<string,string> mapc = new map<string,string>();
    if(trigger.isinsert && trigger.isAfter){
     for(account acc : trigger.new){
       sbc.add(acc.accountnumber);
     }
    }
    for(country__c c: [select id,name,Checkbox__c from Country__c where name IN:sbc and Checkbox__c =true ]){
        mapc.put(c.name,c.name);
    }   
   for(account acc : trigger.new){
    if(mapc.containsKey(acc.accountnumber)) {
        contact con = new contact();
        con.lastname =  acc.name;
        con.phone = '8867414079';
        con.email ='test@gmail.com';
        con.AccountId = acc.id;
        lstcon.add(con);
}
  }
    if(lstcon !=null){
        insert lstcon;
    }
}

Auto populate a  field Email "Email " on contact  with an  custom Email field "EMAIL__c" from the Account object or possibliy from Account Object itself, needs to happen when a user selects the account and saves the record.


trigger childtoparent on Contact (before update) {
    set<id> accids = new set<id>();
    for(contact con : trigger.new){
        if(con.Status__c == 'Active'){
        accids.add(con.AccountId);
        }
    }
    map<id,account> mapacc = new map<id,account>([select id,name,industry,email__c from account where id IN: accids  ]);
    for(contact con : trigger.new){
        if(mapacc.get(con.accountid).industry == 'Banking'){
        if( mapacc.containsKey(con.accountid)){
        con.email = mapacc.get(con.AccountId).email__c;
        }
    }
    }
}

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger childtoparent caused an unexpected exception, contact your administrator: childtoparent: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.childtoparent: line 10, column 1



trigger childtoparent on Contact (before update) {
    set<id> accids = new set<id>();
    for(contact con : trigger.new){
        if(con.Status__c == 'Active'){
        accids.add(con.AccountId);
        }
    }
    map<id,account> mapacc = new map<id,account>([select id,name,industry,email__c from account where id IN: accids and industry = 'Banking'  ]);
    for(contact con : trigger.new){
       // if(mapacc.get(con.accountid).industry == 'Banking'){
        if( mapacc.containsKey(con.accountid)){
        con.email = mapacc.get(con.AccountId).email__c;
        }
  //  }
    }
}