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
Carole Reynolds1Carole Reynolds1 

Populating APEX Maps with object ID's as keys and object names as values

The invoices.get( ... ) in the last line returns null because the invoices keySet contains keys which are not Opportunity__c.Id's like I expected. I am doing something like this in the following execute anonymous code:

Id key = '006G000000TZ2f9IAD';
Map<Id, Invoice1__c> invoices = new Map<Id, Invoice1__c> ([SELECT Opportunity__c
                                                                , Name
                                                            FROM Invoice1__c
                                                            WHERE Opportunity__c = :key]);

system.debug('Created Map. Number of Invoice names mapped=' + invoices.size());
system.debug('Invoices.Get=' + invoices.get(key));

I would like to be able to pull the Invoice1__c.Name from the Map something like:

String invoiceName = invoices.get(newTicket.sbx_Opportunity__c).Name;

1. How do I properly populate a Map of <OpportunityID, Invoice1__c.Name>. Like this <006G000000TZ2f9IAD, 'Inv-0561'>

2.  What are the Id's that I currently see in the invoices variable keySet?
Best Answer chosen by Carole Reynolds1
~Onkar~Onkar
Hi Ravin,


Map<Id, Invoice1__c> invoices = new Map<Id, Invoice1__c> ([SELECT Opportunity__c
                                                                , Name
                                                            FROM Invoice1__c
                                                            WHERE Opportunity__c = :key]);

Following Query hold the key in map as Invoice Id not Opportunity ID.




Try this may be it will help you.

Map<Id, Invoice1__c> invoices = new Map<Id, Invoice1__c>();
for(Invoice1__c obj : [SELECT Opportunity__c
                                                                , Name
                                                            FROM Invoice1__c
                                                            WHERE Opportunity__c = :key]){

invoices.put(obj.Opportunity__c,obj.Name);
}