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
Andréa de FariaAndréa de Faria 

Prevent Moving Stage based on Status in a related event

Hello, How are you?

Please, I would like to know if you could help me with the following: how can I prevent the Opportunity Owner from moving an Opportunity from Stage A to Stage B if the field C in the Event related to the Opportunity is different from D.

Being the the field C is a picklist and D is a string?

Thank you a lot!
Best Answer chosen by Andréa de Faria
CharuDuttCharuDutt
Hii Andrea
Try Below Trigger
trigger OppTrigger on Opportunity (before update) {
    boolean bFlag;
    set<Id> OppId = new set<Id>();
    for(opportunity opp: trigger.new){
        if(opp.StageName != trigger.oldMap.get(Opp.Id).StageName){
            oppId.Add(Opp.id);
        }
    }
    list<Event> lstEvent=[SELECT Id, WhatId FROM Event where WhatId In : OppId];
    for(Event e:lstEvent){
        if(e.Field_C__c != e.Field_D__c){
            bFlag = true;
        }
    }
    for(opportunity opp: trigger.new){
        if(bFlag == true){
            opp.AddError('Cannnot Change Stage');
        }
    }
    
}
Please Mark It As Best Answer If It Helps
Thank You!

All Answers

CharuDuttCharuDutt
Hii Andrea
Try Below Trigger
trigger OppTrigger on Opportunity (before update) {
    boolean bFlag;
    set<Id> OppId = new set<Id>();
    for(opportunity opp: trigger.new){
        if(opp.StageName != trigger.oldMap.get(Opp.Id).StageName){
            oppId.Add(Opp.id);
        }
    }
    list<Event> lstEvent=[SELECT Id, WhatId FROM Event where WhatId In : OppId];
    for(Event e:lstEvent){
        if(e.Field_C__c != e.Field_D__c){
            bFlag = true;
        }
    }
    for(opportunity opp: trigger.new){
        if(bFlag == true){
            opp.AddError('Cannnot Change Stage');
        }
    }
    
}
Please Mark It As Best Answer If It Helps
Thank You!
This was selected as the best answer
Andréa de FariaAndréa de Faria
Wow! It's great!! 

It really blocked the Opportunity Owner from moving to the next stage, however, and I go to the Event Page and try to update field C (in order to meet the criteria to move to the next stage), it shows the following error:

We can't save this record because the “Event” process failed. Give your Salesforce admin these details. This error occurred when the flow tried to update records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: OppTrigger: execution of BeforeUpdate caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Event.Field_C__c (). You can look up ExceptionCode values in the SOAP API Developer Guide. Error ID: 1662549184-86665 (838309929)ook up ExceptionCode values in the SOAP API Developer Guide. Error ID: 1662549184-86665 (838309929)

Am I doing something wrong?