+ Start a Discussion
oceanofstarsoceanofstars 

Null value in trigger

 

Hi All
I have an object called company profile. It has only 3 fields in it. Account, Telephone,company details. Now my scenario is whenever anybody creates a new company profile and add a telephone no and if it matches to any account phone then it should display that account in account field in the company profile object.Account is the lookup in the company profile. Here is the trigger i wrote i am able to save the trigger but when i create a record it is saying nullvalue on line 21. I mentioned the line 21 in RED below. Please have a look at it and let me know where did i make a mistake
trigger relatedaccount on companyprofile__c (after insert, after update) {
Map<String, companyprofile__c> mapPhones = new Map<String, companyprofile__c>();
    for (companyprofile__c c: Trigger.new) { 
        if (c.telephone__c != null) {
            mapPhones.put(c.telephone__c, c);
        }
    }
     List<String> listPhones = new List<String>();
    Map<String, Account> mapAccounts = new Map<String, Account>();
    for (list<Account> acts : [Select Id, phone__c from Account where phone__c in :listPhones]) {
        for (Account act : acts) {
            mapAccounts.put(act.phone__c, act);
        }
    }
    // Creating a List of companyprofile__c which will be inserted at the end.
    List<companyprofile__c> listcompanyprofiles = new List<companyprofile__c>();
    for (companyprofile__c c: mapPhones.values()) {
        companyprofile__c ca = new companyprofile__c(Name = c.Name); 
        ca.Account__c = mapAccounts.get(c.telephone__c).ID; 
        listcompanyprofiles.add(ca);
    }
    update listcompanyprofiles;
}

 

sfdcfoxsfdcfox

The null value error is likely correct. It happens when there isn't a matching phone number in the database. Make just one small change:

 

 

    for (companyprofile__c c: mapPhones.values()) {
        if(mapAccounts.get(c.telephone__c)==null)
            continue;
        companyprofile__c ca = new companyprofile__c(Name = c.Name); 
        ca.Account__c = mapAccounts.get(c.telephone__c).ID; 
        listcompanyprofiles.add(ca);
    }

 

 

oceanofstarsoceanofstars

HI

 

Thanks for the reply..now i am able to save the record .Now when i create a new record in company profile and when i add a telephone__c and it has one account but it is not displaying in the company profile.