update a related record value using Map and Apex class?
Example 1:
How to create and update existing contact records using map and apex class
global void execute(Database.BatchableContext BC, List<sObject> scope) { List<Data_Feeds__c> feeds = (List<Data_Feeds__c>) scope; Set<String> lastNames = new Set<String>(); for (Data_Feeds__c f : feeds) { lastNames.add(f.Name); } Map<String, Contact> contacts = new Map<String, Contact>(); for (Contact c : [ select Id, LastName from Contact where LastName in :lastNames ]) { contacts.put(c.LastName, c); } for (Data_Feeds__c f : feeds) { Contact c; if (contacts.containsKey(f.Name)) { c = contacts.get(f.Name); } else { c = new Contact(LastName = f.Name); contacts.put(f.Name, c); } c.FirstName = f.First_Name__c; c.AccountId = f.Primary_Account_ID__c; c.AccContRole__c = f.Account_ID__c; } upsert contacts.values(); }
Example 2:
To update map values using the apex trigger and below is the example code
trigger IndustrytoAcctOpp on Customer_Product_Line_Item__c ( before insert, before update ) { Map<String,String> imap = new Map<String,String>(); for ( Industry_Definition__c i : [ SELECT Id, Market_Segment__c, Strategic_Industry__c FROM Industry_Definition__c ] ) { imap.put( i.Market_Segment__c, i.Strategic_Industry__c ); } Map<Id,Customer_Product_Line_Item__c> map_AccountID_CPLI = new Map<Id,Customer_Product_Line_Item__c>(); for ( Customer_Product_Line_Item__c cpli : trigger.new ) { cpli.Strategic_Industry__c = imap.get( cpli.Industry_Segment__c ); map_AccountID_CPLI.put( cpli.Account__c, cpli ); } List<Account> list_AccountsToUpdate = new List<Account>(); for ( Account a : [ SELECT Id, Strategic_Industry__c FROM Account WHERE Id IN :map_AccountID_CPLI.keySet() ] ) { a.Strategic_Industry__c = map_AccountID_CPLI.get( a.Id ).Strategic_Industry__c; list_AccountsToUpdate.add( a ); } update list_AccountsToUpdate; }