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
TechEd_ProgrammerTechEd_Programmer 

Updating list with Map Value

So I cannot seem to figure this one out. I do not use maps all that often and I am having a hard time determining how to update a value from it.

 

I am trying to update the inventory by subtracting the value from the map. Pleas see the code below:

trigger PO_Request_Update_Inv_Transit on PO_Request__c (after update) {

	PO_Request__c[] porequest;
	
	Set<Id> poSet = new Set<Id>();
	Set<Id> podetailSet = new Set<Id>();
	Set<Id> inventorySet = new Set<Id>();
	Map<String, Decimal> popartMap = new Map<String, Decimal>();
	List<Inventory__c> inventoryList = new List<Inventory__c>();
	List<PO_Request_Detail__c> porequestdetailList = new List<PO_Request_Detail__c>();
	
	for(PO_Request__c po:porequest)
	{
		poSet.add(po.Id);
		Decimal invQty = 0;
		
		If(po.PO_Req_Status__c == 'Approved')
		{
			porequestdetailList = [Select Id, PO_Request__c, Part_Num__c, Qty__c from PO_Request_Detail__c where PO_Request__c IN : poSet];
			
			for(PO_Request_Detail__c prd:porequestdetailList)
			{
				popartMap.put(prd.Part_Num__r.Id, prd.Qty__c);
				podetailSet.add(prd.Part_Num__c);
			}
			
			inventoryList = [Select Part_Num__r.Id, Qty__c from Inventory__c where Part_Num__c IN :podetailSet];
			
			for(Integer i = 0; i < inventoryList.size(); i++)
			{
				if(popartMap.containsKey(inventoryList[i].Part_Num__r.Id))
				{
					inventoryList[i].Qty__c = inventoryList[i].Qty__c - 
				}
				update inventoryList;
			}
		}
	}
}

 My main problem is how to get the mapped value and use it in my calculation to update.

 

inventoryList[i].Qty__c = inventoryList[i].Qty__c - ???

 

Thank you for your help.

Best Answer chosen by Admin (Salesforce Developers) 
RChintalapatiRChintalapati

Its simple:

 

just use: popartMap.get(inventoryList[i].Part_Num__r.Id). 

 

Word of advice: Use the DML operation after the for loop or you may run into governor limits

All Answers

VaasuVaasu
First of all it looks like your code will not go in to the loop at line # 12 as the array variable is not been populated with any data.

TechEd_ProgrammerTechEd_Programmer

Thank you for your reply. I have used this structure multiple times with success. It is the Map usage that I need help wih please. Can you offer assistance on that?

RChintalapatiRChintalapati

Its simple:

 

just use: popartMap.get(inventoryList[i].Part_Num__r.Id). 

 

Word of advice: Use the DML operation after the for loop or you may run into governor limits

This was selected as the best answer
TechEd_ProgrammerTechEd_Programmer

Thank you! I figured it was simple, it was jsut escaping me. And thank you for the advice on the DML.