I want to insert a record in the database. If it meets certain criteria, it should be inserted in lead, if not, it should be added in contacts. I'm not able to achieve this. Its a before insert trigger on lead object. If the trigger completes properly, it gets updated in leads irrespective of its insertion in contacts. Please help..
2 Answers
You could do something like this in an after trigger. It has the downside of burning up an Id on Lead as each Lead needs to be inserted into the Database first
if (trigger.isInsert) {
List<Lead> leadsToConvertToContacts = new List<Lead>();
for(Lead l : Trigger.new) {
if (l.SomeCriteria__c == 'Blah') {
leadsToConvertToContacts.add(eDel);
}
}
List<Contact> newContacts = new List<Contact>();
for (Lead l : leadsToConvertToContacts) {
// Create Contact from Lead
DeleteLeadsClass dlc=new DeleteLeadClass();
dlc.deleteLead(l.id);
}
// delete leadsToConvertToContacts;
insert newContacts;
// Or use upsert
}
And so i added an apex class called DeleteLeadsClass as follows: global class DeleteLeadsClass{
public void deleteLead(String IDs){
Lead lead1=[Select id from lead where id=:IDs];
delete lead1;
} }
This works perfectly fine. :)
-
It gives me an error that DML statement of delete cannot work in trigger.new or trigger.old. Can u help me regarding this?– SamCommented Oct 24, 2013 at 4:49
-
Maybe it will only work in the trigger.isUpdate event. See techman97.wordpress.com/2012/03/29/… Commented Oct 24, 2013 at 8:53
-
i got through.. I made a small apex class for deleting passing this lead's ID to it and deleting it in that class. Its working fine now. Lots of thanks :-)– SamCommented Oct 24, 2013 at 12:45
-
Thats good. Feel free to update my code with a working example. Thanks Commented Oct 24, 2013 at 12:50
What you can do is..create after insert trigger.. check for condition if its true --> insert contact record and delete this instance from Lead.
-
i tried it. It won't let me use the delete statement. C an u tell me how to do that?– SamCommented Oct 24, 2013 at 4:50