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
SV MSV M 

Unable to populate Account field on Contact using Maps

Hi, I am trying to populate Account Type on Contact by creating custom picklist 'Type' using Maps.

public class ContactAccountMap {
    public void accountMap() {
        Set<Id> accountIds = new Set<Id>();
        List<Contact> conList = [SELECT Id, Name, Type__c, AccountId FROM Contact];
        for(Contact con : conList) {
            accountIds.add(con.AccountId);
        }
        List<Account> accList = [SELECT Id, Name, Type FROM Account WHERE Id IN:accountIds];
        //System.debug('accounts'+accountIds);
        //System.debug('contacts'+conList);
        Map<Id,Account> accMap = new Map<Id,Account>([SELECT Id, Name, Type FROM Account WHERE Id in:accountIds]);
        for(Contact con : conList) {
            if(con.AccountId != NULL) {
                con.Type__c = accMap.get(con.AccountId).Type;
            }
        }
    }
}

The code doesn't throw any errors but the I am not getting the functionality. Can someone help me with this...

Thanks in advance...
ShirishaShirisha (Salesforce Developers) 
Hi Sai,

Greetings!

I can see that you are already querying the Accounts records based on the AccountIds in the below line:
Map<Id,Account> accMap = new Map<Id,Account>([SELECT Id, Name, Type FROM Account WHERE Id in:accountIds]);
So,I don't think you need to get the Type by referring the AccountId again.So,you can simply map the value of Type directly as below:
 
con.Type__c = accMap.Type;

Can you please try the above line and let me know,if it works for you.

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri​​​​​​​
 
SV MSV M
Hi Shirisha, The code snippet doesn't worked and it throwed an error says 'Variable Type doesn't exist'...