Deleting Any Object You Don’t Own

Each new Salesforce release has me revisiting previous solutions and looking at how they can be improved. One little tidbit that was provided in Winter ’13 is a way to get the SObject type from the Id. In the past, you’d have to do quite a bit of code to determine the type of SObject from the Id. Now all we need to do to get the SObject type from an ID is:


id.getSObjectType();

This got me thinking that I could rewrite my Contact deletion webservice and have it be more generic to delete any object I don’t own.

I call this SuperDelete. It is almost identical to my Contact deletion class except now it checks to see what the object type is first and instantiates a new object with that ID so it can be deleted. It then checks to see what access level the requesting user has. In this case, the user needs to have at least Edit Access.

global without sharing class SuperDelete {
webService static String deleteRecord(Id id) {
sObject so = id.getSObjectType().newSObject(id=id);
try {
UserRecordAccess ura = [select RecordId, HasEditAccess from UserRecordAccess where UserId = :UserInfo.getUserId() and RecordId = :id];
if (ura.HasEditAccess)
delete so;
else
throw new deleteException('Error deleting');
return '';
} catch (Exception e) {
return e.getMessage();
 }
 }
}

This webservice can be invoked from a custom JavaScript button that needs to be created on each object you want to use this on:

{!REQUIRESCRIPT("/soap/ajax/22.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/22.0/apex.js")}

if (confirm("Are you sure?")) {
 var result = sforce.apex.execute("SuperDelete","deleteRecord", {id:"{!Contact.Id}"});
 var errorDiv = document.getElementById('errorDiv_ep');
 if (result != '') {
 errorDiv.innerHTML = result;
 errorDiv.style.display = 'block';
 }
 else window.location.replace('/003/o');
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s