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
Akash DeokarAkash Deokar 

apex trigger logic is not working

I have written trigger on opportunity as below, if opportunity stage gets update to verbal agreement then SAP CODE and LEGAL ENTITY should be available or it will through error.

But output is not getting as i wanted, please check below logic from code and output. 

Apex Trigger:
trigger SAP_CODE on Opportunity (before Update) {
   for(Opportunity opp:trigger.new){
           
        if(opp.StageName=='Verbal Agreement'){
            System.debug('Stage is verbal');
            
            if(opp.Legal_Entity_Name__r.Name==null){
                System.debug('inside entity name');
                opp.addError('Oppotunity cannot move to 80% as LE is not present');
                
                 If(opp.Legal_Entity_Name__r.SAP_CODE__c==null){
                    opp.addError('Oppotunity cannot move to 80% as SAPE CODE is not present');
                    System.debug('SAP code not available');
                }
            }
            else{
            system.debug('SAP code is available');
            }
        }
    }
}

Code to run trigger:
Opportunity opp= new Opportunity(name='demo', stagename='Qualification', closedate=system.today());
Account demoacc=[Select id from Account where name='Demo Account'];
opp.accountid=demoacc.id;
insert opp;
System.debug('opp inserted');
opp.stagename='verbal agreement';
try{
update opp;
}catch(Exception e)
{e.getmessage();}
Legal_Entity__c LEDemo = new Legal_Entity__c();
insert LEDemo;
opp.Legal_Entity_Name__c=LEDemo.id;
System.debug('LE inserted');
try{
update opp;
}catch(Exception e)
{e.getmessage();}
LEDemo.SAP_CODE__c='0008';
system.debug('SAP CODE updated');
try{
update opp;
}catch(Exception e)
{e.getmessage();}

Output:
User-added image
Akash DeokarAkash Deokar
I got one point the field i am trying to check(sap_code__c) is not getting fetch....please tell me how to call relationship object's field.