[SalesForce] Code without sharing information

If with sharing or without sharing is not specified in the following, will only the controller run with sharing? I think only apex controller and anonymous block will respect the OWD and sharing settings of the user who is running the code.

  • Apex Controller
  • Anonymous Block
  • Apex Trigger

For Apex Trigger, it doesn't matter whether the with sharing or without sharing is there or not. Triggers will always execute in System Mode.

Please correct if my understanding is wrong.

Best Answer

Note from Using the with sharing or without sharing Keywords:

The with sharing keyword allows you to specify that the sharing rules for the current user be taken into account for a class. You have to explicitly set this keyword for the class because Apex code runs in system context. In system context, Apex code has access to all objects and fields— object permissions, field-level security, sharing rules aren’t applied for the current user. This is to ensure that code won’t fail to run because of hidden fields or objects for a user. The only exceptions to this rule are Apex code that is executed with the executeAnonymous call and Chatter in Apex. executeAnonymous always executes using the full permissions of the current user.

So in your first paragraph, you are not quite right. For a class that does not specify a sharing setting, Execute Anonymous will enforce sharing every time. If the class is called from an Apex Trigger, it will run without sharing when not specified. For a controller extension, it will inherit the active sharing setting, which from the StandardController will be with sharing. I believe that if you write a custom Controller, it will have nothing to inherit and will actually run without sharing, but I would have to check.

As for which setting to use on Apex Classes called from an Apex Trigger, the system will enforce the class sharing setting if one is specified:

The sharing setting of the class where the method is defined is applied, not of the class where the method is called. For example, if a method is defined in a class declared with with sharing is called by a class declared with without sharing, the method will execute with sharing rules enforced.

Related Topic