1

Having a little issue when working with a map and performing a field update in my apex code. I'm writing a batch that updates a field on the Contact object based upon a field on a custom object (lets call it Custom__c). I stored the Contact Id and the custom object using a map. I wish to get the field using a relationship query Different_Custom__r.field_i_need__c but I keep getting an error so I'm sure I'm doing something wrong.

Here's my code-

public void execute(Database.BatchableContext BC, List<PAO__c> scope) { 
    Set<Id> conIdSet = new Set<Id>();
    Map<Id, Custom__c> updateConsMap = new Map<Id, Custom__c>();
    
    for(Custom__c custom : [SELECT Id, Contact__c, PAO__c, POA__r.field_i_need__c FROM Custom__c WHERE POA__c IN :scope])            
            conIdSet.add(custom.Contact__c);
            updateConsMap.put(custom.Contact__c, custom);
        }
    
    List<Contact> conList= new List<Contact>([SELECT Id, field_to_update__c FROM Contact WHERE Id IN :conIdSet]);
    
    if(!conIdSet.isEmpty()) {
        for(Contact con :conList) {
            Contact c = new Contact();
            c.Id = con.Id;
            c.field_to_update__c = updateConsMap.get(custom.Contact__c).Policy_Allocation_Option__r.Performance_Lock_Date__c; <---- help here!
            conList.add(c);
    }
        update conList;

    }

this particular error i'm getting is Variable does not exist: custom. I'm not sure why the variable doesnt exist when its defined above... Also, is this going to function correctly?

2

You are attempting to retrieve the value from the map using the contact id but custom is not in scope at this line:

c.field_to_update__c = updateConsMap.get(custom.Contact__c).Policy_Allocation_Option__r.Performance_Lock_Date__c;

Within that loop, con is your contact reference from the list.

for (Contact con :conList) {
    Contact c = new Contact();
    c.Id = con.Id;
    c.field_to_update__c = updateConsMap.get(con.Id).Policy_Allocation_Option__r.Performance_Lock_Date__c;
    conList.add(c);
}

That said, there's likely a problem here. You're iterating conList and then adding new contact instances into this same list. Performing the update will throw an exception about duplicate ids.

Rather than adding a new contact, simply set the field on the con reference and then update conList.

for (Contact con :conList) {
    con.field_to_update__c = updateConsMap.get(con.Id).Policy_Allocation_Option__r.Performance_Lock_Date__c;
}

update conList;
2
  • Beat me to the punch. +1 – Derek F Dec 15 '20 at 17:50
  • perfect, thank you so much! – sfn00b Dec 15 '20 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.