I need to run an SOQL command, as admin just like system.runAs(u) in controller.
Is there a way to do this.
I need to run an SOQL command, as admin just like system.runAs(u) in controller.
Is there a way to do this.
To run a query as "an administrator", use the "without sharing" keyword within a class:
public without sharing class Utility {
public static Account[] queryAccounts() {
return [SELECT Id, Name, Industry FROM Account LIMIT 100];
}
}
While you are still running the query as the current user, the current user's sharing is ignored, which means that the query will execute as if the user were an administrator.
Also note that within triggers, the code runs by default "without sharing", so it is generally not necessary to run "as administrator" unless you're using utility classes (such as the example here).
There is NO way to do this outside of test methods and for good reason.
By default the code will likely be running as an admin user. What you can do though is grab the profile ID for the 'System Administrator' profile, insert a new user using that profile, then run as the new user.
Id profileId = [select Id from UserProfile where Name = 'System Administrator' limit 1].Id
User u = new User();
// fill in required fields (well documented)
u.UserProfileId = profileId; // think this is the right field name, double check
insert u;
System.RunAs(u.Id);
Yes as the error suggest, the
System.runAs()
method can be used only in Test Classes. As @LaceySnr suggested, all APEX code run with "View All" and "Modify All" permissions.
If your apex classes have "With Sharing" Keyword, then all the Sharing rules for logged-in user apply.