+ Start a Discussion
Irene SlessIrene Sless 

Get values from Map with objects

In my Contact trigger I've created a Map based on a query where the Map stores the Account object. It is meant to find the corresponding Account based on the foreign key field customerId, and from which I need to insert the Account's ID and another custom field into the new Contact. When I check on accMap being null, it says it is, but when I use 'isEmpty' it goes into the subsequent code, yet it says there are no values (ie it fails when accessing the values in 'a.Id', saying this statement 'c.AccountId = a.Id;' is referencing a null value).

Can someone tell me what is wrong please?

    Set<string> customerIds = new Set<string>();

    for(Contact c : trigger.new){
        string customerId = c.AccredoCustomerID__c;
        if(!customerIds.contains(customerId)){
            customerIds.add(customerId);
        }
    }

    List<Account> accs = [Select AccredoID__c, Id, AccredoPrimaryContact__c From Account Where AccredoID__c In :customerIds];
    Map<string, Account> accMap = new Map<string, Account>(accs);

    for(Contact c : trigger.new){
        string customerId = c.AccredoCustomerID__c;

       Account a = accMap.get(customerId);

        if(!accMap.isEmpty()){
                Account a = accMap.get(customerId);
                c.AccountId = a.Id;
                if (a.AccredoPrimaryContact__c == c.AccredoId__c){
                    c.Primary_Contact__c = true;
               }
            }
        }
    }
Best Answer chosen by Irene Sless
Bhanu MaheshBhanu Mahesh
Hi Irene,

List<Account> accs = [Select AccredoID__c, Id, AccredoPrimaryContact__c From Account Where AccredoID__c In :customerIds];
 Map<string, Account> accMap = new Map<string, Account>(accs);

Try by populating the map. Please try the beloow code

List<Account> accs = [Select AccredoID__c, Id, AccredoPrimaryContact__c From Account Where AccredoID__c In :customerIds];
Map<string, Account> accMap = new Map<string, Account>();
for(Account acc :accs){
   accMap.put(acc.AccredoID__c,acc);
}

Regards,
Bhanu Mahesh
 

All Answers

Bhanu MaheshBhanu Mahesh
Hi Irene,

List<Account> accs = [Select AccredoID__c, Id, AccredoPrimaryContact__c From Account Where AccredoID__c In :customerIds];
 Map<string, Account> accMap = new Map<string, Account>(accs);

Try by populating the map. Please try the beloow code

List<Account> accs = [Select AccredoID__c, Id, AccredoPrimaryContact__c From Account Where AccredoID__c In :customerIds];
Map<string, Account> accMap = new Map<string, Account>();
for(Account acc :accs){
   accMap.put(acc.AccredoID__c,acc);
}

Regards,
Bhanu Mahesh
 
This was selected as the best answer
Irene SlessIrene Sless
Hi Bhanu
Yes, that worked. It's confusing though as I've seen code samples where this is not required, as it says the List populates the Map. Seems it only works that way if the Id is used as the lookup though, whereas I'm using a string.
It's working now though :)
Thanks!