function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ankit dangreankit dangre 

Facing :-( System.NullPointerException: Attempt to de-reference a null object) my code s correct and have n no error but while copy contact phone to account phone got an above error plz do the needful help

trigger UpdateAccountPhoneBasedOnContact on Contact (after insert,after update) {
    set<id> setAccid=new set<id>();
    map<id,Account>mapAcc=new map <id,Account>();
    for(contact con:trigger.new){
        if(trigger.isInsert && con.AccountId!=null && con.phone!=null){
            setAccid.add(con.AccountId);
        }
        if(trigger.isUpdate && con.AccountId!=null && con.phone!=trigger.oldMap.get(con.Id).phone){
            setAccid.add(con.AccountId);
        }
    }
    if(!setAccid.isEmpty()){
        for(account acc:[select id,name,phone from account where id in:setAccid]){
            mapAcc.put(acc.id,acc);
        }
    }
    list<account> updateAcclist=new list<account>();
    if(!mapAcc.isEmpty()){
        for(contact con:trigger.new){
            if(mapAcc.containsKey(con.AccountId)){
                mapAcc.get(con.AccountId).phone=con.Phone;
                updateAcclist.addAll(mapAcc.values());
            }
        }
    }
}
ankit bansalankit bansal
The code seems fine (I ran it in my org) can you paste the complete stack trace, however it can be written in a more efficient manner - 
trigger UpdateAccountPhoneBasedOnContact on Contact (after insert,after update) {
    map<id,Account>mapAcc = new map<id,Account>();
    if(trigger.isAfter){
        for(contact con:trigger.new){
            if((trigger.isInsert && con.AccountId!=null && con.phone!=null) || (trigger.isUpdate && con.AccountId!=null && con.phone!=trigger.oldMap.get(con.Id).phone)){
                Account acc = new Account();
                acc.id = con.AccountId;
                acc.phone = con.phone;
                mapAcc.put(acc.id,acc);
            }
        }
        
        if(!mapAcc.isEmpty()){          
            update mapAcc.values();
        }
    }
}


 
ankit bansalankit bansal
Maybe your error is coming from some other trigger on the contact or account , for that purpose please attach the complete stack trace of the exception here.