+ Start a Discussion
DarrellDDarrellD 

Update Multiple Fields with Before Insert Trigger - Only Updating One Field

Seems like missing something obvious. The below statement is only updating the first field when its called from a Trigger. If I then edit the record and save, it updates the 2nd field. I obviously am expecting it to update both fields at once.

 

public class UpdateAddressTypeManager{


/* Updates value of AddressType record when received from SalesForce to SalesForce
Lookup fields cannot be mapped from Connections */

// Update Address value
public static void handleAddrProvUpdate(Address_Type__c[] addrtypes) {

// create a set of all the unique Remote Address ids
// Remote_AddressId__c stores text value of SalesForce Id for updating
Set<String> remoteaddr = new Set<String>();
Set<String> remoteprov = new Set<String>();
for(Address_Type__c at : addrtypes){
remoteaddr.add(at.Remote_AddressId__c);
remoteprov.add(at.Remote_ProviderId__c);
}
System.debug('RemoteAddr set = ' + remoteaddr);
System.debug('RemoteProv set = ' + remoteprov);

// create list of Address__c items with matching remote address id
List<Address__c> addrids = [Select Id, Remote_Address_Id__c From Address__c Where Remote_Address_Id__c in:remoteaddr];
List<Contact> provids = [Select Id, Remote_ProviderId__c From Contact Where Remote_ProviderId__c in:remoteprov];


// Verify size of address list
System.debug('AddressId size ' + addrids.size());

// Verify size of provider list
System.debug('ProviderId size ' + provids.size());

// creates map of Address_Type and Address for updating
Map<Address_Type__c,Id> addrmap = new Map<Address_Type__c,Id>();
Map<Address_Type__c,Id> provmap = new Map<Address_Type__c,Id>();

for(Address_Type__c at : addrtypes) {
For(Address__c ad : addrids) {
If(ad.Remote_Address_Id__c == at.Remote_AddressId__c)
addrmap.put(at,ad.id);
}
For(Contact cont : provids) {
If(cont.Remote_ProviderId__c == at.Remote_ProviderId__c)
provmap.put(at,cont.id);
}
}

System.debug('Address Map ' + addrmap);
System.debug('Provider Map ' + provmap);


// Only updating first field. If put in different order, still just does first one
for(Address_Type__c atupd : addrtypes){
atupd.Provider__c = provmap.get(atupd);
atupd.Address__c = addrmap.get(atupd);
}
}
}

 

Thanks,
Darrell

arizonaarizona

Having a quick cursory glance my hunch is you need type to list of addresses:  That is there are many addresses to each type.  So for an address type you need a list of addresses.  Otherwise the last address overwrites the previous address of the same type.

 

// creates map of Address_Type and Address for updating
Map<Address_Type__c,List<Id>> addrmap = new Map<Address_Type__c,List<Id>>();
Map<Address_Type__c,List<Id>> provmap = new Map<Address_Type__c,List<Id>>();