Just for the reference, the code in your original question comes with several problems. This is not to nag on your code, but rather to allow you understand how to improve it.
- You try to select records, that are not yet committed to the database
- You want to delete records that were inserted in the same context as the delete
- You are issuing SOQL and DML Queries inside a loop
Fixing 1 is easy - change the before insert to after insert.
The 2nd one is a little tricky, because for this to work you need an @future annotated method in another class (as crop1645 correctly pointed out). Therefore, create an apex class that exposes a single method like this:
public class TriggerHelper { @future public static void deleteRecords(Set<Id> objectsIdsToDelete) { delete [Select Id from MC4SF__MC_Subscriber_Activity__c where Id in : objectsIdsToDelete]; } }
Then call this static method from your code. The 3rd one is also an easy one to fix: First, collect a set of ids to delete, then process them in one step. This is done in the deleteRecords-Method, so no need to worry about this again.
Finally, your code should look somewhat like this:
trigger MCSubscriberActivityDelete on MC4SF__MC_Subscriber_Activity__c (after insert) { TriggerHelper. deleteRecords(Trigger.newMap.keySet()); }
This is of course not the best way, if (and you'd have to try that for yourself) the Mailchimp doesn't mind the errors caused by a validation rule. This would actually save you from keeping unwanted records in your recycle bin for several days and would be a much cleaner solution to the problem.