With sharing doesn't work with triggers

Scenario 1:

Sample Code:

Trigger:

trigger sample on Account (after insert, after update) {
    Sample1.test(trigger.new);
}

 public with sharing class Sample1{
    public static void test(List<Account> acctList){
        List<Employee__c> empList = new List<Employee__c>();
        for(Account a : acctList){
            Employee__c e = new Employee__c(Name = 'Testing');
            empList.add(e);        
        }      
        insert empList; 
    }
}

If an user with no access to Employee object creates an account or updates an account, Employee record with the name, "Testing" will be created with created by name as him/her.

Scenario 2:

Sample Code:

trigger sample on Account (before update) {
    
    for ( Account a : trigger.new ) {
        a.Count__c = [ SELECT COUNT() FROM Employee__c ];
    }
    
}

If an user with no access to Employee object updates an account, Count field will be updated with no of records in Employee object.

Scenario 3:

Sample Code:

trigger sample on Account (before update) {
    
    sample1.test(trigger.new);
    
}

public with sharing class Sample1 {

    public static void test(List<Account> acctList) {
        for (Account a : acctList ) {
            a.Count__c = [ SELECT COUNT() FROM Employee__c ];        
        }      
    }
    
}

If an user with no access to Employee object updates an account and OWD is Private, Count field will be updated to zero.

If an user with no access to Employee object updates an account and OWD is Public Read Only or Public Read/Write, Count field will be updated with no of records in Employee object.

No comments:

Post a Comment