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
bathybathy 

Apex trigger to attach products to opportunities based on opportunity record types

Hi Gurus,

One new requirement, We need to attach products to opportunities based on opportunity record types. Is this possible through Apex triggers?

Please help

Thanks,
Yamini
~Onkar~Onkar
Yes Possible.

You need to use following Object in your trigger

Product2
Pricebook2
Pricebookentry
Opportunity line Item (for Insert)

Keep in mind opportunity line item not support more than 1 price book in same opportunity.

~Thanks
Onkar Kumar


Hargobind_SinghHargobind_Singh
Yes, you should be able to do that. Here is some sample code, to add products on all opportunities. You can modify this to add your record-type conditions, and product combinations. Be careful about the governor limits though. 

//The trigger adds a set of default products to an opportunity as soon as it gets created. 
//code can be modifed to have different set of products for different conditions, e.g. record-types or owners 
//the trigger uses for-inside-for, which isn't good for governor limit, so be careful while you implement this or modify this to remain within governor limits. 
trigger AddProductsToOpportunity on Opportunity (after insert) {
	
	String priceBookName = 'Standard'; 
	List<String> productCodeList = new List<String>{'GC1040', 'IN7080', 'SL9040'}; 
	List<PricebookEntry> pbeList = [Select Product2.ProductCode, UnitPrice, Product2Id, priceBook2Id From PricebookEntry  where Product2.ProductCode in :productCodeList and Pricebook2.Name = :priceBookName ]; 
	
	if(pbeList.size() > 0 ){
		ID priceBookID = pbeList[0].priceBook2Id; 
		List<OpportunityLineItem> oliList = new List<OpportunityLineItem>(); 		
		for(Opportunity o: trigger.new){
			for(PricebookEntry pbe: pbeList){
				OpportunityLineItem oli = new OpportunityLineItem(); 
				oli.OpportunityId = o.id; 
				oli.PricebookEntryId = pbe.id; 
				oli.Quantity = 1; 
				oli.UnitPrice = pbe.UnitPrice; 
				oliList.add(oli); 
			}
		}
		insert oliList; 
	
	}//	if(pbeList.size() > 0 )

}


bathybathy
Thanks for your replies guys.
hs1  What if I had long list of products codes. can i get them with a SOQL Query?
bathybathy

Hi hs1,

I am a new bie

can you please provide full code for this, I did not see opportunity record type checking anywhere in the code.
bathybathy
Hi @hargobindh_singh I tried your trigger but it is not working can you please help?

thanks,
Hargobind_SinghHargobind_Singh

Hi Bathy, 
 

Can you let me know your exact requiement, i.e., are you trying to add different products, based on different record-types ? 

Can you give an example, with record-type name and products, so that I can tweak this code for you ? 
 

bathybathy
Thanks for responding Hargobind. 

Yes my requirement is to add the products based on the record type. We currenlty have 9 record types for opportunities. And the products must be added based on each record type. 


Hargobind_SinghHargobind_Singh
Bathy, am assuming that you have a list of ProductCodes for every record-type, let me give you some code and you can edit it as per your requiements. 

You can edit the recordtypeID_1,2,3 as per your needs, and also update code1,2,3 etc as per your needs. 

If this doesn't work, paste your modified code, and i can help you in finding out why it is not working 


//The trigger adds a set of default products to an opportunity as soon as it gets created. 
//code can be modifed to have different set of products for different conditions, e.g. record-types or owners 

trigger AddProductsToOpportunity on Opportunity (after insert) {
	
	String priceBookName = 'Standard'; 
	List<String> productCodeList = new List<String>(); 
	
	Map<String, List<String>> rTypeProductCodesMap = new Map<String, List<String>>(); 
	//add your record-types and product codes here. 
		
	rTypeProductCodesMap.put('RecordTypeID_1', new List<String>{'Code1','Code2','Code3'});
	rTypeProductCodesMap.put('RecordTypeID_2', new List<String>{'Code4','Code5','Code6'});
	rTypeProductCodesMap.put('RecordTypeID_3', new List<String>{'Code7','Code8','Code9','Code10'});
	
	// Logic
	//get all PriceBookEntry, and keep them in a map
	//based on record-type, take out pricebook entries. 
	for(String s:  rTypeProductCodesMap.keySet()){
		productCodeList.addAll(rTypeProductCodesMap.get(s)); 
	}
	List<PricebookEntry> pbeList = [Select Product2.ProductCode, UnitPrice, Product2Id, priceBook2Id From PricebookEntry  where Product2.ProductCode in :productCodeList and Pricebook2.Name = :priceBookName ]; 
	Map<String, PricebookEntry> codePbeMap = new Map<String, PricebookEntry>(); 
	for(PricebookEntry pbe: pbeList){
		if(pbe.Product2.ProductCode !=null && pbe.Product2.ProductCode.length()>0  ){
			codePbeMap.put(pbe.Product2.ProductCode, pbe); 
		}
	}
	//loop through opportunities and add appropriate PriceBook Entries 
	
	if(pbeList.size() > 0 ){
		ID priceBookID = pbeList[0].priceBook2Id; 
		List<OpportunityLineItem> oliList = new List<OpportunityLineItem>(); 		
		for(Opportunity o: trigger.new){
			//if recordtype ID is in the list above 
			if(rTypeProductCodesMap.containsKey(o.RecordTypeID)){
				//Loop on product codes  
				for(String code1 :rTypeProductCodesMap.get(o.RecordTypeID ) ){
					//get pbe entry and create an OLI entry 
					if(codePbeMap.containsKey(code1)){
						OpportunityLineItem oli = new OpportunityLineItem(); 
						oli.OpportunityId = o.id; 
						oli.PricebookEntryId = codePbeMap.get(code1).id; 
						oli.Quantity = 1; 
						oli.UnitPrice = codePbeMap.get(code1).UnitPrice; 
						oliList.add(oli); 
					}
				}
				
			}
		}
		insert oliList; 
	}//	if(pbeList.size() > 0 )

}


bathybathy
thank you so much for your reply Hargobind. I will get back to you with all my requirements and let you know
Gabriel Meneses 10Gabriel Meneses 10
@Hargobind_Singh , I think this trigger would work great for my needs. Is there a way to do the following;

We have a custom field in the Request object, that field contains an ISBN, is it possible to create a trigger that would look at that field, search our products for that ISBN and then add it to the opportunity as a product?

This would be amazingly helpful.
RaoSRaoS
Hi @hargobindh_singh I tried your trigger but it is not working?  can you help?
 
Vaishnavi Gupta 5Vaishnavi Gupta 5
Hello  @Hargobind_Singh the trigger that you have wriiten in the last i am pasting the same code in developer console there it is showing  one variable which is not declared that RecordTypeID can you please help me out as well as i am new to coding part so can you please give the overview of the code too it will really be helpful for me                        



Thankyou in Advance