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
AdaptiDevAdaptiDev 

Limit SOQL results based on user security

I want to limit the results of a SOQL statements so that this SOQL only returns the records the user is allowed to see.

 

eg.

 

[SELECT FirstName, LastName FROM Contact]  should result in a List of Contacts that the active user has access to.

 

I know you can do a RunAs(user) but this can only be used in a Test class.

 

 

I 'm looking for this a long time, but I don't find solutions for this problem.

 

Thank you.

Best Answer chosen by Admin (Salesforce Developers) 
Edwin VijayEdwin Vijay

Use the "with sharing" keyword when you declare your apex class

 

public with sharing sampleclass { public fn() { [Select id,/name from contact ] } }

 

Now your query will return only records which are visible to the user who executes this class...

 

U can find more about this in the Apex Language reference... 

 

All Answers

Edwin VijayEdwin Vijay

Use the "with sharing" keyword when you declare your apex class

 

public with sharing sampleclass { public fn() { [Select id,/name from contact ] } }

 

Now your query will return only records which are visible to the user who executes this class...

 

U can find more about this in the Apex Language reference... 

 

This was selected as the best answer
AdaptiDevAdaptiDev

Thank you for the tip.

 

I also looked in the Apex language reference and found the RunAs(user).  But I will try this right now!