I want to write trigger which can automatically convert leads into account, contact and opportunity.
What I have tried so far:
trigger ConvertLead on Lead (after insert, after update,before insert,before update) {
if(trigger.isBefore){
Map<String, Lead> leadMap = new Map<String, Lead>();
for (Lead lead : System.Trigger.new) {
//We don't treat an email address that isn't changing during an update as a duplicate.
if ((lead.Email != null) && (System.Trigger.isInsert || (lead.Email != System.Trigger.oldMap.get(lead.Id).Email))){
//Checking whether another new lead isn't also a duplicate
if (leadMap.containsKey(lead.Email)) {
lead.Email.addError('Another new lead has the same email address.');
} else {
leadMap.put(lead.Email, lead);
}
}
}
list<opportunity> objOpportunity = new list<opportunity>();
//Finding all the leads in the database that have the same email address as any of the leads being inserted or updated.
for (Lead lead : [SELECT Name, Email, IsConverted, ConvertedAccountId, ConvertedContactId, ConvertedOpportunityId FROM Lead WHERE Email IN :leadMap.KeySet()]){
Lead newLead = leadMap.get(lead.Email);
Opportunity ObjOpp = new Opportunity();
ObjOpp.AccountId = lead.ConvertedAccountId;
ObjOpp.Name = lead.Name;
ObjOpp.StageName = 'Prospecting';
ObjOpp.CloseDate = System.today();
objOpportunity.add(ObjOpp);
system.debug('*************ConvertedAccountId************'+lead.ConvertedAccountId);
//newLead.Email.addError('A lead with this email address already exists.');
}
insert objOpportunity;
system.debug('*************objOpportunity************'+objOpportunity);
}
if(trigger.isAfter){
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
for (Lead lead : Trigger.new) {
//Converting those leads whose Status is equal to Web
if (lead.isConverted == false && lead.LeadSource == 'Web'){
system.debug('************lead*************'+lead);
Database.LeadConvert objLeadConvert = new Database.LeadConvert();
objLeadConvert.setLeadId(lead.Id);
String oppName = lead.Name;
objLeadConvert.setOpportunityName(oppName);
objLeadConvert.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult objLeadConvertResult = Database.convertLead(objLeadConvert);
}
}
}
}
When creating new lead if we found duplicate (or same) email id in System, we should create only opportunity under Account who has same email.