Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

When doing SOQL Queries, how I can I ensure that I only return the set of Objects that the current user has access to?

Imagine I query for Accounts, and I display a list of links to those Accounts on a VisualForce page. I only want to list those Accounts that the user has access to, otherwise the user clicks on a link but will get an Access Denied, which is not what we want.

How do I do that?

share|improve this question
1  
You mean current user? –  Artur Kępczyński Feb 14 at 11:26
    
Sure, updated. Thanks. –  Willem Mulder Feb 14 at 11:28
    
@adtennant - answer fit your requiments –  Artur Kępczyński Feb 14 at 11:31
add comment

1 Answer 1

up vote 7 down vote accepted

Define the class that your SOQL query is within as with sharing.

This is covered by the online documentation here.

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.

And here is an example:

Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For example:

public with sharing class sharingClass 
{
    // Code here
}
share|improve this answer
    
Excellent. Exactly what I need. –  Willem Mulder Feb 14 at 11:31
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.