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
Waqar Hussain SFWaqar Hussain SF 

How to access values from Map

I am mapping accout with a custom object In a trigger. how can I access custom object fields from Account. 
Here is my code..

Map<ID, Account> mapaccounts = new Map<ID, Account>([SELECT Id, Name, phone FROM Account]);
    List<custom_object__c> RecodList = new List<custom_object__c>();
    RecodList.add( new custom_object__c(Name=mapaccounts.get().Name,  Phone__c =mapaccounts.get().Phone, custom_field__c =mapaccounts.get().account_field__c ))
Grazitti TeamGrazitti Team
Hi Vickey,

You have to pass the id of account in the map to get the record. For Example:
 
Map<ID, Account> mapaccounts = new Map<ID, Account>([SELECT Id, Name, phone,account_field__c FROM Account]);
    List<custom_object__c> RecodList = new List<custom_object__c>();
    RecodList.add( new custom_object__c(Name=mapaccounts.get(ID_OF_ACCOUNT).Name,  Phone__c =mapaccounts.get(ID_OF_ACCOUNT).Phone, custom_field__c =mapaccounts.get(ID_OF_ACCOUNT).account_field__c ))
When you pass account id in get method this will return the account record and then your corresponding field.

Please mark it best if this helps you.

Regards,
Grazitti Team
www.grazitti.com
 
Waqar Hussain SFWaqar Hussain SF
actually my recordList is in the for loop. and also how can i get iD of account from map??
ManojjenaManojjena
I think below code will solve your problem .
Map<Id, Account> mapaccounts = new Map<Id, Account>([SELECT Id, Name, phone FROM Account]);
    List<custom_object__c> recodList = new List<custom_object__c>();
  for(String accId : mapaccounts.keySet()){
        recodList.add( new custom_object__c(Name=mapaccounts.get(accId).Name,  Phone__c =mapaccounts.get(accId).Phone);
    }
Suraj Tripathi 47Suraj Tripathi 47
Hi Waqar,

"Try this code."

Map<Id, Account> accmap= new Map<Id, Account>([SELECT Id, Name, phone FROM Account]);
    List<customobject__c> customList = new List<customobject__c>();
  for(String accId : mapaccounts.keySet()){
        customList.add( new customobject__c(Name=accmap.get(accId).Name,  Phone__c =accmap.get(accId).Phone);
    }


If you find your Solution then mark this as the best answer. 


Thank you!

Regards 
Suraj Tripathi