0

I am new to SFDC.I am writting a triger to update the Fax field of Account object if I change the fax field of contact object. please correct me where I am doing wrong, below is my code.

trigger Trigger_UpdateAccountFaxOnContactFax on Contact (after update) {
    List<id> lstConAccid = new List<id>(); //stores the acount id
    List<id> lstConId= new List<id>(); // stores the contat id
    for(Contact c : trigger.new)
    {
        lstConAccid.add(c.AccountId);
        lstConid.add(c.Id);
    }

    Map<id, Contact> mapCon = new Map<id, Contact>( [ Select  id, fax from Contact ] );
    List<Account> lstAcc = new List<Account>( [ select id, fax  from account where id in :lstConAccid] );
    for( Account a : lstAcc)
    {
        a.Fax = mapCon.get(a.id).fax;
    }}

I am getting the below error:

NUll Exception on a.Fax = mapCon.get(a.id).fax; statement

1
  • Your map mapCon is contactId vs contact and you are trying to get AccountId in a.Fax = mapCon.get(a.id) Jul 4, 2017 at 10:14

2 Answers 2

2
Map < id, Contact > mapCon = new Map < id, Contact > ();
for (Contact con: [Select id, accountid, fax from Contact]){
    mapCon.put(con.AccountId, con);
}
List < Account > lstAcc = new List < Account > ([select id, fax from account where id in : lstConAccid]);
for (Account a: lstAcc){
    a.Fax = mapCon.get(a.id).fax;
}
1
0

For the above trigger scenario I have written a test class.It is working properly and giving code coverage > 75 %. please let me know what improvements are required in my code.

@isTest
public class Test_Trigger_UpdateAccFaxOnConFax {    
    public static testMethod void isUpdateFax(){
        //Create the Account object
        Account a = new Account( Name = 'testAccount' , Fax ='111111111' );
        Insert a;
        //Create a Contact object
        Contact c = new Contact ( LastName = 'TestContact', Fax = '123456789', Accountid = a.Id );
        Insert c;
        //Now, our trigger will fire on After update event so update the Records
        c.Fax = '222222222';
        update c;
        List<account> lstAcc = new List<Account>( [select id, fax from Account where id = :c.AccountId ] );
        System.assertEquals('222222222', '222222222');
    }
} 

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .