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
Lukesh KarmoreLukesh Karmore 

help me with below trigger

i have  custom field product type on Opportunity  , when oppolineItem is created  i have to checck productFamily equal to product type  if not  then show error my code is

trigger CheckProductTypeonOppLineItem_whenItIsCreated on OpportunityLineItem (after insert) {
set<id> setIds=new set<id>();

list<OpportunityLineItem> opplist=[select id,opportunity.Product_type__c, Product2.Family from OpportunityLineItem where id In:setIds];
for(OpportunityLineItem o:opplist){
    if(o.Product2.Family != o.opportunity.Product_type__c){
      o.addError('Product family must be same ');
any other way ot writing above trigger .
Thank you
AbhinavAbhinav (Salesforce Developers) 

Are you getting any issue.Please specify.

mukesh guptamukesh gupta
Hi Lokesh,

Please use below code:
trigger CheckProductTypeonOppLineItem_whenItIsCreated on OpportunityLineItem (after insert) {
set<id> setOppIds=new set<id>();
Map<Id, Opportunity> oppMap = [Select Product_type__c from opportunity where id IN: setOppIds];   
//list<OpportunityLineItem> opplist=[select id,opportunity.Product_type__c, Product2.Family from OpportunityLineItem where id In:setIds];
for(OpportunityLineItem o:Trigger.New){
    if(o.Product2.Family != oppMap.get(o.opportunityId).Product_type__c){
      o.addError('Product family must be same ');

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Suraj Tripathi 47Suraj Tripathi 47

Lokesh with the help of trigger you cant get the error message as in case of after insert

and also you cant get the error message in case of before insert because you cant get the id of Opportunity

so you should use Vf page to achieve this

Thank You

Lukesh KarmoreLukesh Karmore
Thank you so much for your kind reply Abhinav,mukesh and suraj , i solved it by myself

trigger CheckProductTypeonOppLineItem_whenItIsCreated on OpportunityLineItem (before insert) {
  set<id> prdtIds=new set<id>();
  set<id> oppIds=new set<id>();
  for(OpportunityLineItem ){
  opportunity opp=[select id ,product_type__c from opportunity where id in:oppIds];
  product2 pd=[select id ,family from product2 where id in:prdtIds];
 list<OpportunityLineItem> oliList=new list<OpportunityLineItem>();
  for(OpportunityLineItem ){
      oli.addError('Product family does not match');