Skip to Content

TheBlogReaders.com

Salesforce.com, PHP, MySQL, Javascript, Ajax, Htacces

How to Access Query Results (SOQL) Values using MAP in Apex Class?

Be First!

How to Access Query Results (SOQL) Values using MAP in Apex Class?

For Example:

This is a After Trigger in Account:
for (Account acc : Trigger.new) {
accId.add(acc.Id);
}
map<Id, Contact> mapContacts = new map<Id, Contact>([Select Id, FirstName, LastName, RecordTypeId, AccountId, Email, Fax from Contact where AccountID =: accId]);

ssing above approach, the Results in your Map being keyed by the Id (Contact ID) field not for the other contact values like firstname, lastname, etc.

You need to populate your Map using the otehr than Id then we need do to manually by iterating over the results of the query like below method:
Another Way:
map<Id, Contact> mapContacts = new map<Id, Contact>();
list<Contact> listContacts = new map<Id, Contact>([Select Id, FirstName, LastName, RecordTypeId, AccountId, Email, Fax from Contact where AccountID =: accId]);

if(!listContacts.isEmpty()){
for(Contact con: listContacts) {
mapContacts.put(con.Id, con);
}
}

using this way after queried the data in the list and need to loop thr each contacts data and put it the each data into the map (mapContacts) with Key (Contact Id) & Values (Contact Results)

For More information related to Map, please click the below link for salesforce doc:

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_map.htm

(960)

Previous
Next

Leave a Reply