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
Liubov KornevaLiubov Korneva 

Opportunity Trigger Before Update doesn't work

So here is the scenario, I want to have an error message when user click Save after he changes Opportunity Stage from 10% Probability to 20% probability. I am using Related list Object Contact Role so not sure if this is what causing the issue

trigger ContactValidate on Opportunity ( before update ) {

    Set<ID> oppId = new Set<ID>();
    
    for(Opportunity o : trigger.new){
        if(o.StageName != Trigger.oldMap.get(o.Id).StageName){
            oppId.add(o.Id);
        }
    }
    //If(oppId!=null){ 
    If(!oppId.IsEmpty()){ 
        List<OpportunityContactRole> OCR = [select id from OpportunityContactRole where OpportunityId=:oppId];
            if( OCR.size()==0 ){
                for(Opportunity o : trigger.new){
                    if(o.Probability == 10){
                        o.addError('No Contact associated with opportunity');
                     }    
                }
           }
        }
   }

 
Dushyant SonwarDushyant Sonwar
Hi Liubov,
change this line
  List<OpportunityContactRole> OCR = [select id from OpportunityContactRole where OpportunityId=:oppId];
with this
  List<OpportunityContactRole> OCR = [select id from OpportunityContactRole where OpportunityId in :oppId];
Hope this helps...
AnjaneyluAnjaneylu
  hi  Liubov Korneva and sushyant sonwa.
i am new to coding.
may i know what is the purpose of keeping this statement in the above program.    Set<ID> oppId = new Set<ID>();
Thanking you in Advance,,
Rahul BorgaonkarRahul Borgaonkar
Hi,

Set<ID> oppId = new Set<ID>();
It is a collection of unique IDs you are collecting in the loop. You are initializing this variable here first.

    for(Opportunity o : trigger.new){
        if(o.StageName != Trigger.oldMap.get(o.Id).StageName){
            oppId.add(o.Id);
        }
I hope its clarify your question.

Regards