I wrote a really simple trigger on Contact After Insert
which isn't working as expected. The expected behaviour would be to delete contacts created from Leads converted that had the field Account_to_be_converted_in__c
populated.
public class TriggerContactDeleteFarmingContacts implements Triggers.Handler {
public void handle () {
List<id> ContactsToDelete = new List<id> ();
Map<id,Contact> Mapcontacts= new Map<id,Contact> ();
for(Contact C: (List <Contact>) Trigger.new) {
Mapcontacts.put(C.id,C);
}
System.debug('Mapcontacts: ' + MapContacts);
for(Lead L: [SELECT Account_to_be_converted_in__c,ConvertedContactid FROM Lead WHERE isConverted = True AND ConvertedContactid in: MapContacts.keySet()]) {
if(MapContacts.keyset().contains(L.ConvertedContactid) && !String.isBlank(L.Account_to_be_converted_in__c)) {
ContactsToDelete.add(L.ConvertedContactId);
}
}
Database.delete(ContactsToDelete);
}
}
For some reason I still don't see the query isn't returning any row, but if I do it on query editor it returns the expected results.
EDIT: (Using on Lead After update Trigger)
public class TriggerLeadDeleteContactonConvert implements Triggers.Handler {
public void handle () {
Map <id,Lead> MapOldLeads = (Map<id,Lead>) Trigger.oldMap;
List <id> contactsToDelete = new List <id> ();
for(Lead L:(List <Lead>) Trigger.new) {
if(L.isConverted != MapOldLeads.get(L.id).isConverted && !String.isBlank(L.Account_to_be_converted_in__c)) {
contactsToDelete.add(L.ConvertedContactId);
}
}
Database.delete(contactsToDelete);
}
}
If I try the code above I'm getting this error :
ENTITY_IS_DELETED
So the conversion isn't possible to be achieved.
EDIT 2: (Using Trigger on Lead After Update without using Id but List, still getting same error)
public void handle () {
Map <id,Lead> MapOldLeads = (Map<id,Lead>) Trigger.oldMap;
List <Contact> contactsToDelete = new List <Contact> ();
for(Lead L:(List <Lead>) Trigger.new) {
if(L.isConverted != MapOldLeads.get(L.id).isConverted && !String.isBlank(L.Account_to_be_converted_in__c)) {
contactsToDelete.add(new Contact(id=L.ConvertedContactId));
}
}
delete contactsToDelete;
}