function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
BrandiTBrandiT 

Trigger to Move Custom Object Related List during Lead Conversion

I have a couple custom objects related to the lead record.  When I convert the lead, I want these related list to move over to the Account and Opportunity.

 

I found a trigger on the Appexchange that is supposed to do exactly what I need, but it is not working correctly.  It only moves one record from the related list over.  I need the trigger to move all related list records.

 

Below is the trigger I'm using.  How can I modify this to re-parent all of the related records to the account, not just one of them.  I think it may have something to do with the "break;" line of the code, but don't know enough about Apex to know for sure.

 

trigger UpdateCustomeObject_Trigger on Lead (before update) {

for (Integer i = 0; i < Trigger.new.size(); i++){
    if (Trigger.new[i].IsConverted == true && Trigger.old[i].isConverted == false){
    Set<Id> leadIds = new Set<Id>();
    for (Lead lead : Trigger.new) {
        leadIds.add(lead.Id);
    }
   
    Map<Id, CustomObject__c> entries = new Map<Id, CustomObject__c>([select Contact__c, Opportunity__c, Account__c, Lead__c from CustomObject__c where lead__c in :leadIds]);       
    if(!Trigger.new.isEmpty()) {
    for (Lead lead : Trigger.new)  {
    for (CustomObject__c CustomObject : entries.values()) {
    if (CustomObject.Lead__c == lead.Id) {
        CustomObject.contact__c = lead.ConvertedContactId;
        CustomObject.opportunity__c = lead.ConvertedOpportunityId;
        CustomObject.account__c = lead.ConvertedAccountId;
        update CustomObject;
        break;
    }
    }
    }
    }
    }
    }
}

BrandiTBrandiT

I found a wonderful resource that was able to help me with this.  Here is the code I'm using:

 

trigger UpdateOHObject_Trigger on Lead (after update) {

  Map<Id, Lead> leadMap = new Map<Id,Lead>();
  Lead parent;
 
  for (Integer i = 0; i < Trigger.new.size(); i++){
    if (Trigger.new[i].IsConverted == true && Trigger.old[i].isConverted == false) {
      leadMap.put( Trigger.new[i].Id, Trigger.new[i]);
    }
  }
   
  if( leadMap.size() > 0 ) {
      Set<Id> leadIds = leadMap.keySet();
      List<Opportunity_Headings__c> allChildren =
        [select Id, Opportunity__c, Account__c, Lead__c from Opportunity_Headings__c where lead__c in :leadIds];      
 
 System.debug(allChildren);
   
      for ( Opportunity_Headings__c child : allChildren ) {
        if ( leadMap.containsKey( child.Lead__c ) ) {
           // lookup the parent lead
           parent = leadMap.get( child.Lead__c );
           // update the fields on the child object
           child.opportunity__c = parent.ConvertedOpportunityId;
           child.account__c = parent.ConvertedAccountId;
        }
      }

System.debug(allChildren);

    //try {
      update allChildren;
   // } catch( Exception e ) {
         // could put something here to notify on error
         // otherwise it fails silently
   // }
     
  }
}

 

 

Thanks again Robert!!

BrivoSFDCBrivoSFDC

Thanks BrandiT for posting this. I'd found a similar piece of code and couldn't figure out how to get all of the related items to work. It was very helpful. My issue now is getting my test code to work properly. We have a 3 step approval process that was created through the UI, not code. Below is a snippet the test code that I'm trying to run.

 

**********

@isTest

private class TestTriggerDemoUpdate {
static testMethod void TestReferralUpdate() {
// Insert the Lead
List<Lead> leads = new List<Lead>();
Lead leadt = new Lead (FirstName ='fname', LastName ='test', Company ='myCompany', Dlr_Eval_Approval_Requested__c =True, Dlr_App_Dealer_Application_Received__c=True, Dlr_App_DFS_DSO_Approval_Requested__c=True, Dlr_App_DFS_DSO_Approved__c=True);
insert leadt;

 

// Insert the demo Record
Demo__c Demo = new Demo__c (Lead__c = leadt.Id);
insert Demo;

 

// setup ProcessInstance
ProcessInstance approvalProcess = new ProcessInstance();
approvalProcess.TargetObjectId = leadt.Id;

 

//approvalProcess.ProcessDefinitionId = ;
approvalProcess.Status = 'Started';

 

//approvalProcess.CurrentNodeId = ;
//insert approvalProcess;

// Create an approval request for the lead
Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
req1.setComments('Submitting request for approval.');
req1.setObjectId(leadt.Id);
req1.setNextApproverIds(new Id[] {UserInfo.getUserId()});

 

// Submit the approval request for the lead
Approval.ProcessResult result1 = Approval.process(req1);

 

// Verify the results
System.assert(result1.isSuccess());
System.assertEquals('Pending', result1.getInstanceStatus(), 'Instance Status'+result1.getInstanceStatus());

 

// Approve the submitted request

// First, get the ID of the newly created item
List<Id> newWorkItemIds = result1.getNewWorkitemIds();

// Instantiate the new ProcessWorkitemRequest object and populate it

Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
req2.setComments('Approving request.');
req2.setAction('Approve');
req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});

// Use the ID from the newly created item to specify the item to be worked
req2.setWorkitemId(newWorkItemIds.get(0));

// Submit the request for approval
Approval.ProcessResult result2 = Approval.process(req2);

// Verify the results

System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());

//Convert the Lead
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(leadt.Id);
LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);

//Requery for the referral record to see if it is updated
Demo__c ref_upd = [select Account__c, Demo_Contact__c, Opportunity__c from Demo__c where Lead__c = :leadt.Id];

//Check that the test passed
System.assertEquals(ref_upd.Account__c,[Select ConvertedAccountId From Lead Where Id = :Demo.Lead__c].ConvertedAccountId);
System.assertEquals(ref_upd.Demo_Contact__c,[Select ConvertedContactId From Lead Where Id = :Demo.Lead__c].ConvertedContactId);
System.assertEquals(ref_upd.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :Demo.Lead__c].ConvertedOpportunityId);

**********

 

However, I get the following error:

 

System.DmlException: Process failed. First exception on row 0; first error: NO_APPLICABLE_PROCESS, No applicable approval process found.: []

 

Does anyone know if there is a way to simulate an approval process? Any help would be MUCH appreciated.