Apex method to delete single record of any salesforce object.
To this apex method we pass recordId and with the help of getSObjectType we get the object name and prepare a dynamic SOQL query.
@AuraEnabled
public static string deleteRecord(Id recordId){
try{
List<Sobject> record = Database.query('Select Id from ' + String.valueOf(recordId.getSObjectType())+ ' where id=:recordId');
if(!record.isEmpty() && record.size() >0) {
delete record;
return 'Success';
} else {
return 'False';
}
}catch(exception e){
return e.getMessage();
}
} How the method works
@AuraEnabledmakes the method callable from a Lightning component.recordId.getSObjectType()returns the type of the Id, so the method works for any object.- A dynamic query checks that the record exists. If it does, the record is deleted and the method returns Success. Otherwise it returns False, and a failure returns the error text.
Points to note
- The query is not needed. Deleting by Id works directly, and a missing record raises a clear error.
- Returning text such as Success or False forces the component to compare strings. Throwing an exception is the usual way to report errors to LWC.
- There is no permission check. Use the object describe to see if the user can delete the record type.
Simpler version
@AuraEnabled
public static void deleteRecord(Id recordId) {
try {
Schema.DescribeSObjectResult d = recordId.getSObjectType().getDescribe();
if (!d.isDeletable()) {
throw new AuraHandledException('You do not have permission to delete this record.');
}
Database.delete(recordId);
} catch (DmlException e) {
throw new AuraHandledException(e.getDmlMessage(0));
}
} Calling it from LWC
import deleteRecord from '@salesforce/apex/RecordController.deleteRecord';
handleDelete() {
deleteRecord({ recordId: this.recordId })
.then(() => { /* show a success message */ })
.catch((error) => { console.error(error.body.message); });
} Replace RecordController with the name of your Apex class.
FAQ
Does this delete child records?
Salesforce deletes the children that are set to cascade delete, such as the Contacts of an Account.
Why not use the deleteRecord function from lightning/uiRecordApi?
You can. It deletes a record without Apex and is the simplest choice when you only need to delete it by Id.