+ Start a Discussion
Vigneshwaran LoganathanVigneshwaran Loganathan 

Need Trigger for below condition

APEX trigger in Opportunty, whenever the stage is 100% & closed
go to corresponding opportunity line item and get the product code and go the product object and reduce the STOCK field by the qty mentioned in the Opportunity line item
shiv@SFDCshiv@SFDC
I actully don't know custom fields which you are using on your object. But I writter trigger to give you Idea.
 
trigger updateProductQuantity ON Opportunity(after update)
{
	Set<Id> opIdSet = new Set<Id>();
	Set<Id> productIdSet = new Set<Id>();

	for(Opportunity op : Trigger.new){
		
		if(op.StageName = '100%Closed' && Trigger.newMap.get(op.Id).stageName != '100%Closed') // you give name when you opportunity is closed won and closed
		{
			opIdSet.add(op.Id);
		}
	}

	Map<ProductId,Integer> productToConsumedQuantity = new Map<ProductId,Integer>() ;
	for(OpportunityLineItem oppLI :[SELECT Id, Product2, Quantity FROM OpportunityLineItem WHERE OpportunityId IN: oppLIList] )
	{
		Integer temp ;
		if(productToConsumedQuantity.get(oppLI.Product2) == null )
		{
			productToConsumedQuantity.put(oppLI.Product2,(oppLI.Quantity != null?oppLI.Quantity : 0)) ;
		} else {
			temp = productToConsumedQuantity.get(oppLI.Product2) ;
			temp += oppLI.Quantity != null? oppLI.Quantity : 0 ;
			productToConsumedQuantity.put(oppLI.Product2,temp) ;
		}
		
		productIdSet.add(oppLI.Product2) ;
	}

	List<Product2> prodList = new List<Product2>();
	for(Product2 product : [SELECT Id, CustomQuantityField__c FROM Product2 WHERE Id IN: productIdSet]){

		product.CustomQuantityField__c = product.CustomQuantityField__c - productToConsumedQuantity.get(product.Id) ;
		prodList.add(product) ;
	}

	If(prodList.size() > 0)
	{
		update prodList ;
	}
}
If this post helps you please mark answer as solution.
Thanks !