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
Arek Stegienko DevArek Stegienko Dev 

Event Trigger to Convert Lead

I'm writing an event trigger that will convert a lead when an event of a specific record type is created.  Here's what I've got so far, however, I'm getting stuck on checking for the right record type in the trigger and/or creating the right record type event in the test class:

 

trigger ConvertLead on Event (after insert)
{
  // Loop through all the events
  for (Event event : trigger.new)
  {
    // Check if this is a 1st tour event
    if (event.RecordType ==
        [SELECT Id FROM RecordType WHERE Name = '1st Tour' AND SObjectType = 'Event' LIMIT 1])
    {
      // Get the lead that's associated with this event
      Lead lead = [SELECT Id FROM Lead WHERE Id =: event.WhoId];

      // Create a new LeadConvert object
      Database.LeadConvert convert = new database.LeadConvert();
    
      // Get and set the converted lead status
      LeadStatus convertStatus = [SELECT MasterLabel FROM LeadStatus WHERE IsConverted = true LIMIT 1];
      convert.setConvertedStatus(convertStatus.MasterLabel);
    
      // Set the owner
      convert.setOwnerId(event.OwnerId);

      // Convert the lead
      Database.LeadConvertResult result = Database.convertLead(convert);
      System.assert(result.isSuccess());
    }
  }
}

 

  static testMethod void ConvertLeadTestMethod()
  {
    // Create the lead, insert it, and add the event
    Lead lead = new Lead(FirstName = 'Test', LastName = 'Lead');
    insert lead;
    Event event = new Event(WhoId = lead.Id,
                  RecordType = [SELECT Id FROM RecordType WHERE Name = '1st Tour' AND SObjectType = 'Event' LIMIT 1],
                  DurationInMinutes = 60, ActivityDateTime = datetime.now());
    insert event;
  }

 I'm fairly new to apex so any and all help is very much appreciated.

 

Thanks.

Andy BoettcherAndy Boettcher

Arek,

 

You're on the right track - but there are a few "best practice" things I want to get in front of you first:

 

  • Don't put SOQL inside of loops (for loops) - do that SOQL statement before you enter the loop, save it as a variable, and reference that variable within the loop.
  • Same with the Lead Id.  If you run a SOQL query into a Map outside of the loop and reference that map within - that will help avoid the SOQL limits as well.

For your question at hand - what error messages or other fail conditions are you seeing in the test log?

 

-Andy