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
shyam Sundar 101shyam Sundar 101 

Help Me on This Trigger!!!

Once i choose product in OpportunityProduct the QtyOnHand__c Field i have in Prdocut2 is getting reduced fine. But I made a Query on Opportunity to fetch the StageName. If Stage is ClosedLost the previous value must get added to QtyOnHand__c . This adding inventory when oppurtunit lost is not working.

This is my trigger!! help me with the code.

trigger RemainingQuant on OpportunityLineItem (after insert, before update) {

  
    set<id> PIds = new set<id>();
  
    String o =  [select StageName From Opportunity ][0].StageName;
   for(OpportunityLineItem opli : Trigger.new){
       PIds.add(opli.Product2Id);
   } 
   
         
     list<Product2> pList = [select id, name , QtyOnHand__c from Product2 where Id IN : PIds];  
     
   
   
   
     for(Product2 p : pList){
      
         for(OpportunityLineItem op : Trigger.new){
             if(p.id == op.product2Id ){ 
             
            
                 if(Trigger.isInsert){
                     if(op.Quantity > p.QtyOnHand__c){
                         op.Quantity.addError(' no availability of stock in Product ');
                     }
                     
               
                    p.QtyOnHand__c-= op.Quantity;
                 


              
}               
    
     
                 if(Trigger.isUpdate){
                 
                 if(o == 'Closed Lost'){
                                     
                     p.QtyOnHand__c += (Trigger.oldMap.get(op.Id).Quantity).intValue();
                        
                        
                }        
                        
                    
                 }}
             }
             
     
   
    
    update pList;
 
 } 
}