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
DharaneshDharanesh 

Without Sharing for only one DML statement in a sharing class

Hello All,

I have a controller which is currently in with sharing mode. In that class there are lot of DML statements and i need to execute one of the DML statement in without sharing mode. Is this possible? If yes how?

Thanks in Advance. 
karthikeyan perumalkarthikeyan perumal
Hello, 

try something like below, 

Try to putting your with out sharing DML statement in seprate class  and call that  invoke that class method in with sharing class constructer or where you want refer. 

something like below, 

without sharing class with DML statement
 
public without sharing class accountUtil {
    public void getAccounts() {
       List<Account> lstacc=new List<account>();
       List<Account> lstacc1=new List<account>();
       lstacc=[select Id, Name from Account limit 1];
       
       for(Account a:lstacc)
       {
       a.Name=a.Name+'Updated';
       lstacc1.add(a);
       }
     
       update lstacc1;
    }
}

with sharing class  also included without sharing class method, 
 
public with sharing class accountEdit {
    public account[] accounts { get; set; }
    public void accountEdit() {
    accountUtil util= new accountUtil ();
        util.getAccounts();
        save();
        
        return null;
    }
    public void save() {
    List<Account>updateAc= new List<Account>();
        try {
            accounts=[Select Id, Name,phone from Account Limit 1];
            for( Account Acc: accounts)
            {
            Acc.phone ='4587974646';
            updateAc.add(Acc);           
            }
            
            update updateAc;
            
        } catch(Exception e) {
            ApexPages.addMessages(e);
        }
    }
}

it works in my org without having any error, 

the above solutions is not worked for you. kinldy refer below 2 URLs for the same issue read that very carfully. its may helps to get some Idea. 

http://salesforce.stackexchange.com/questions/16121/sfdc-understanding-with-sharing-without-sharing-unspecified-sharing-classes

http://salesforce.stackexchange.com/questions/73392/does-with-sharing-only-apply-to-1st-entry-point-of-code


Hope this will Help you, 

Mark Best ANSWER if its works or you have clear these points. 

Thanks
karthik








 
DharaneshDharanesh
Hi Karthik,

Thanks for the help, i will give it a try.