This trigger is basically fired on before insert & before update.
I am trying to automatically convert lead to Account,Contact & Opportunity.
My condition is when an Same Name Lead is inserted then only its other name is updated without creating duplicate lead for the same name & also updating an Opportunity CloseDate to System.Today()
.
TRIGGER CODE:
trigger UpdateDuplicateRecords on Lead (before insert,before update) {
public list<string> LastName = new list<string>();
public list<string> LastName1 = new list<string>();
public set<ID> ids = new set<ID>();
public list<opportunity> newopp = new list<opportunity>();
list<Lead> leads = [select ID,LastName from lead];
system.debug('===>'+leads);
for (lead newlead :trigger.new) {
LastName.add(newlead.LastName);
system.debug('===>'+LastName);
ids.add(newlead.id);
system.debug('===>'+ids);
}
for (lead oldlead :leads){
LastName1.add(oldlead.LastName);
system.debug('===>'+Lastname1);
}
if (LastName1 != LastName) {
opportunity opp = new opportunity();
opp.closedate = system.today();
leadstatus convertstatus = [select Id,masterlabel from leadstatus where isconverted = true];
for (Lead newlead : trigger.new){
if ((newlead.isConverted==false)) {
database.leadconvert lc = new database.leadconvert();
lc.setleadID(NewLead.ID);
lc.setConvertedStatus(convertStatus.MasterLabel);
database.leadconvertresult lcr = database.convertlead(lc);
system.assert(lcr.isSuccess());
system.debug('===>' + lcr);
}
}
}
update leads;
}
Am Getting Following Error ========>
Error: Invalid Data. Review all error messages below to correct your data. Apex trigger UpdateDuplicateRecords caused an unexpected exception, contact your administrator: UpdateDuplicateRecords: execution of BeforeInsert caused by: System.DmlException: ConvertLead failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, valid leadId is required: []: Trigger.UpdateDuplicateRecords: line 37, column 1