Skip to main content
I want to update the custom Available_Quantity__c field on Inventory__c object when a new record is created on Quantity_Received__c field on Purchase_Orders__c object.

 I want the latest quantity received on Purchase_Orders__c object to be added to the Available_Quantity__c field on Inventory__c object

There is a lookup relationship from Purchase_Orders__c to Inventory__c 

How can i do this with Apex Triggers ? 
1 respuesta
  1. 6 may 2022, 6:39 a.m.
    Hi Eyup,

    try with below code.

    trigger AvailableQuantityUpdate on Purchase_Orders__c (After insert, after update) {

    map<id,string> accdesmap = new map<id,string>();

    set<id> accids = new set<id>();

    If ((trigger.Isupdate ||trigger.Isinsert ) && trigger.Isafter){

    for(Purchase_Orders__c acc: trigger.new){

    If(acc.Inventory__c != Null){

    accdesmap.put(acc.Inventory__c,acc.Quantity_Received__c);

    accids.add(acc.Inventory__c);

    }

    }

    }

    List<Inventory__c> AvailableQuantityUpdate = new List<Inventory__c>();

    List<Inventory__c> intlist = [select id,Available_Quantity__c from Inventory__c where id =:accids];

    for(Purchase_Orders__c acc:trigger.new){

    for(Inventory__c opp:intlist){

    if(accdesmap.containsKey(opp.id)) {

    opp.Available_Quantity__c= accdesmap.get(opp.id);

    AvailableQuantityUpdate.add(opp);

    }

    }

    // }

    If(opptoUpdate.size()>0) {

    update AvailableQuantityUpdate;

    }

    }

    If this helps, please mark it as best answer.

    thanks!!