Saturday, April 7, 2012

Query User access Level in Apex

     With API 24 salesforce has given access to UserRecordAccess table. This gives us more power in querying whether user have access and upto what level so that we can build our VF and apex accordingly.
http://www.salesforce.com/us/developer/docs/api/index_Left.htm#StartTopic=Content/sforce_api_objects_userrecordaccess.htm

I was writing a VF page in which i needed to have a table of sobject records with Edit and del links for each line item. I was using{!URL for} function which would take care of the link automatically. It would even prevent users who do not have permission to edit or delete the record to take it to the page 'you do not have sufficient permission'.

 I thought it would be nice to know if the loggedin user or profile permission can be queried based on which i could display or hide these links instead of user clicking the link and finding out. Thats when i searched i figured it could be handled with Api 24.0

SELECT RecordId, HasReadAccess, HasTransferAccess, MaxAccessLevel
     FROM UserRecordAccess
     WHERE UserId = [single ID]
     AND RecordId = [single ID]      //or Record IN [list of IDs]

so i needed to get info on hasEditAccess and hasDeleteAccess for loggedin user and based on which i displayed or hid the link. It worked like charm.