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

  • Your map mapCon is contactId vs contact and you are trying to get AccountId in a.Fax = mapCon.get(a.id) – Ajay Prakash Dubey Jul 4 '17 at 10:14
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;
}
| improve this answer | |
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');
    }
} 
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.