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
Nagesh ENagesh E 

can i use "delete" command to delete some records using trigger

trigger TobedeleteContact on Contact (after insert, after update) {
    
    List<Contact> contactToBeDeleted = new List<Contact>();
    Set<Id> ownerIds = new Set<Id>();
   for (Contact c : Trigger.new)
      ownerIds.add(c.OwnerId);
      for (Contact c : Trigger.new)
    {        
        if (c.To_Be_Deleted__c == true)
        {                 
                   contactToBeDeleted.add(c);
        }
    }

  if(!contactToBeDeleted.isEmpty())
  {
   delete contactToBeDeleted;
  }

}

 

I am getting error

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

I updated my post to reflect a small error. You need to make sure that there's sufficient access on the method call.

All Answers

sfdcfoxsfdcfox

You can't delete a record involved in a trigger. Instead, create a class with a @future method, and have your asynchronous method delete the record. Your @future method should run after the lock on the rows have been released.

Nagesh ENagesh E

Thanks for quick reply,

i didnot understand what you mean by @future class, if you don't mind can you send me an example.

 

Thanks

sfdcfoxsfdcfox

You would do something like this:

 

 

trigger deleteSelectedContacts on Contact (after insert, after update) {
  Set<Id> contactsToDelete = new Set<Id>();
  for(Contact c:Trigger.new)
    if(c.Delete_This_Record__c)
      contactsToDelete.add(c.Id);
  myAsyncClass.deleteContacts(contactsToDelete);
}

 

global class myAsyncClass {
  @future
  global static void deleteContacts(Set<Id> contacts) {
    List<Contact> contactsToDelete = [select id from contact where id in :contacts];
    Database.delete(contactsToDelete,false);
  }
}

The trick here is that the @future method executes sometime after the trigger has executed and the lock has been released (usually, anyways). This function can therefore delete the records that were previously marked for deletion, usually within a few seconds after processing the trigger (see the documentation on "future annotation" for timing considerations).

 

Edit: Added permission value missing from this post.

Nagesh ENagesh E

Thanks,

still I am getting error:

 

Error: Compile Error: Method is not visible: ToDeleteAsyncClass.deleteContacts(SET<Id>) at line 8 column 3

 

  
sfdcfoxsfdcfox

I updated my post to reflect a small error. You need to make sure that there's sufficient access on the method call.

This was selected as the best answer