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
Kiran MarketingKiran Marketing 

Trigger for Converting Lead Owner

Senario - I have created a button on Contact which when clicked it redirects to Lead page with prepulated fields like company name, address and so on. It has two custom fields one lookup which alows to choose a user who this new lead would be refered to and othe a field which stores the refered by user name. I got this part now the tricky part is i need to write a trigger as when its clicked on saved button the new lead owner should be saved on the refered to user not on the current user. By default lead owner is stored on current user name. Hence i decided to write a trigger before insert and one after insert which sends a email alert to the new lead owner to which this is refered to or created for. Code looks like missing quite a few things here. Any help would be highly appreciated.
public class LeadTriggerHelperClass {
public static void isBeforeInsert(List<Lead> LeaList)
{Lead Lea = New Lead();
 
    If(Lea.RecordTypeid == '01228000000YtCD')
    {
      Lea.OwnerId = Lea.Reffered_To__c;
    	Insert Lea;
    }
}

public static void isAfterInsert(Lead LeaList)
{
    Lead EmailLead = [SELECT id FROM Lead WHERE id = :LeaList.Id];
  String emailMessage ='A New Lead '
             +'Has been Referred '
             +'By a Sales Representative.' 
             +' For Account'+ EmailLead.Company 
             +' Requirement of ' 
             + EmailLead.Description +
             ' Lead Number'
             + EmailLead.ID 
             +' records were not updated successfully.';
        
        Messaging.SingleEmailMessage mail = 
              new Messaging.SingleEmailMessage();
        String[] toAddresses =new String[] {EmailLead.createdBy.email};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('noreply@salesforce.com');
        mail.setSenderDisplayName('Lead Created');
        mail.setSubject('Lead Created');
        mail.setPlainTextBody(emailMessage);
        mail.setHtmlBody(emailMessage);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] 
                           { mail });
  
}
 }

 
Best Answer chosen by Kiran Marketing
SaranSaran
Hi Kiran,

You have add an additional line in your class.

Your class will be like.
 
public class LeadTriggerHelperClass1 {

    public static void isBeforeInsert(List<Lead> LeadList){
	    
	    id recTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('R    ecord_Type_Name').getRecordTypeId();

// instead of hardcoding the recordtypeID you can get it like this. Replace Record_Type_name with your record type name 

	    for(Lead Lea :LeadList){ 
	        If(Lea.RecordTypeid == recTypeId){
	              Lea.OwnerId = Lea.Reffered_To__c;
	        }
	    }
	}
    
    public static void isAfterInsert(set<id> LeadId){
    

        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        
        for(Lead EmailLead :[SELECT id,Company, Description, createdBy.email FROM Lead WHERE id in :LeadId]){
                 String emailMessage ='A New Lead '
                     +'Has been Referred '
                     +'By a Sales Representative.' 
                     +' For Account'+ EmailLead.Company 
                     +' Requirement of ' 
                     + EmailLead.Description +
                     ' Lead Number'
                     + EmailLead.ID 
                     +' records were not updated successfully.';
                     
                 String baseUrl = System.URL.getSalesforceBaseUrl().toExternalForm();
                 
                 emailMessage = emailMessage + '<a href="'+baseUrl+'/'+EmailLead.id +'">'+EmailLead.id+'</a>';
                 
                Messaging.SingleEmailMessage mail =    new Messaging.SingleEmailMessage();
               String[] toAddresses =new String[] {EmailLead.createdBy.email};
                mail.setToAddresses(toAddresses);
                mail.setReplyTo('noreply@salesforce.com');
                mail.setSenderDisplayName('Lead Created');
                mail.setSubject('Lead Created');
             //   mail.setPlainTextBody(emailMessage);
                mail.setHtmlBody(emailMessage);
                mails.add(mail);
        }
    
        Messaging.sendEmail(mails);
    }
}

Hope this might solve your issue.

Thanks

All Answers

viruSviruS
Try This and let me know if any issue

public class LeadTriggerHelperClass {
public static void isBeforeInsert(List<Lead> LeadList){
    
    for(Lead Lea :LeadList){ 
        If(Lea.RecordTypeid == '01228000000YtCD'){
              Lea.OwnerId = Lea.Reffered_To__c;
        }
    }
}

public static void isAfterInsert(Lead LeadList){
    
    
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        
    for(Lead EmailLead :[SELECT id FROM Lead WHERE id in :LeadList]){
        If(Lea.RecordTypeid == '01228000000YtCD'){
             String emailMessage ='A New Lead '
                 +'Has been Referred '
                 +'By a Sales Representative.' 
                 +' For Account'+ EmailLead.Company 
                 +' Requirement of ' 
                 + EmailLead.Description +
                 ' Lead Number'
                 + EmailLead.ID 
                 +' records were not updated successfully.';
            Messaging.SingleEmailMessage mail =    new Messaging.SingleEmailMessage();
           String[] toAddresses =new String[] {EmailLead.createdBy.email};
            mail.setToAddresses(toAddresses);
            mail.setReplyTo('noreply@salesforce.com');
            mail.setSenderDisplayName('Lead Created');
            mail.setSubject('Lead Created');
            mail.setPlainTextBody(emailMessage);
            mail.setHtmlBody(emailMessage);
            mails.add(mail);
        }
    }
    
      Messaging.sendEmail(mails);
   }
 
}
Kiran MarketingKiran Marketing
Viru

It throws an error "Variable does not exist Lea.RecordTypeId" at line no 17 its in the afterinsert method.

In this line If(Lea.RecordTypeid == '01228000000YtCD'){

Kiran
viruSviruS
Oh copy / paste mistake 

Change  Lea to  EmailLead
Kiran MarketingKiran Marketing
Viru

I figured that out and changed it but it throws an error

Error - IN operator must be used with an iterable experssion

in below line (16)

for(Lead EmailLead :[SELECT id FROM Lead WHERE id in :LeadList]

Kiran
viruSviruS
ok Please change 


public static void isAfterInsert(Lead LeadList){


to   
public static void isAfterInsert(list<Lead> LeadList){
 
Kiran MarketingKiran Marketing
Viru

Find the error screen shot below.


User-added image
 
trigger Referedtest on Lead (Before Insert,After Insert) {
LeadTriggerHelperClass1.isBeforeInsert(trigger.new);

}
 
public class LeadTriggerHelperClass1 {
public static void isBeforeInsert(List<Lead> LeadList){
    
    for(Lead Lea :LeadList){ 
        If(Lea.RecordTypeid == '01228000000YtCD'){
              Lea.OwnerId = Lea.Reffered_To__c;
        }
    }
}

public static void isAfterInsert(list<Lead> LeadList){
    
    
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        
    for(Lead EmailLead :[SELECT id FROM Lead WHERE id in :LeadList]){
        If(EmailLead.RecordTypeid == '01228000000YtCD'){
             String emailMessage ='A New Lead '
                 +'Has been Referred '
                 +'By a Sales Representative.' 
                 +' For Account'+ EmailLead.Company 
                 +' Requirement of ' 
                 + EmailLead.Description +
                 ' Lead Number'
                 + EmailLead.ID 
                 +' records were not updated successfully.';
            Messaging.SingleEmailMessage mail =    new Messaging.SingleEmailMessage();
           String[] toAddresses =new String[] {EmailLead.createdBy.email};
            mail.setToAddresses(toAddresses);
            mail.setReplyTo('noreply@salesforce.com');
            mail.setSenderDisplayName('Lead Created');
            mail.setSubject('Lead Created');
            mail.setPlainTextBody(emailMessage);
            mail.setHtmlBody(emailMessage);
            mails.add(mail);
        }
    }
    
      Messaging.sendEmail(mails);
   }
 
}

Kiran

 
Kiran MarketingKiran Marketing
Viru

I got the error figured out. But for some reason Email is not firing.

Kiran
viruSviruS
Can you please send me debug log .. for this trigger methods 
SaranSaran
Hi Kiran,

Below is the code for your scenario.

Trigger:
trigger Referedtest on Lead (Before Insert,After Insert) {
if(trigger.isBefore)
	LeadTriggerHelperClass1.isBeforeInsert(trigger.new);
if(trigger.isAfter)
	LeadTriggerHelperClass1.isAfterInsert(trigger.newMap.keyset());
}

Class : 
 
public class LeadTriggerHelperClass1 {
	
	public static void isBeforeInsert(List<Lead> LeadList){
	    
	    id recTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Record_Type_Name').getRecordTypeId();

// instead of hardcoding the recordtypeID you can get it like this. Replace Record_Type_name with your record type name 

	    for(Lead Lea :LeadList){ 
	        If(Lea.RecordTypeid == recTypeId){
	              Lea.OwnerId = Lea.Reffered_To__c;
	        }
	    }
	}

	public static void isAfterInsert(set<id> LeadId){
    
    	id recTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Record_Type_Name').getRecordTypeId(); 

    	List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        
	    for(Lead EmailLead :[SELECT id,Company, Description, createdBy.email FROM Lead WHERE id in :LeadId]){
	        If(EmailLead.RecordTypeid == recTypeId){
	             String emailMessage ='A New Lead '
	                 +'Has been Referred '
	                 +'By a Sales Representative.' 
	                 +' For Account'+ EmailLead.Company 
	                 +' Requirement of ' 
	                 + EmailLead.Description +
	                 ' Lead Number'
	                 + EmailLead.ID 
	                 +' records were not updated successfully.';
	            Messaging.SingleEmailMessage mail =    new Messaging.SingleEmailMessage();
	           String[] toAddresses =new String[] {EmailLead.createdBy.email};
	            mail.setToAddresses(toAddresses);
	            mail.setReplyTo('noreply@salesforce.com');
	            mail.setSenderDisplayName('Lead Created');
	            mail.setSubject('Lead Created');
	            mail.setPlainTextBody(emailMessage);
	            mail.setHtmlBody(emailMessage);
	            mails.add(mail);
	        }
	    }
    
        Messaging.sendEmail(mails);
    }
}

Hope this will solve you issue.

Let us know if you still have issues.

Thanks
Kiran MarketingKiran Marketing
Saran

System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Lead.RecordTypeId: Class.LeadTriggerHelperClass3.isAfterInsert: line 23, column 1

Thats the error it throws.

Kiran
 
viruSviruS
update line # 2 and add column recordTypeId 

for(Lead EmailLead :[SELECT id,Company,recordTypeId,  Description, createdBy.email FROM Lead WHERE id in:LeadId])
Kiran MarketingKiran Marketing
Viru

I think we are almost there the only part missing is lead ID should be hyperlinked so that from email when they clicks it  goes to the lead directly. Else everything is working.

Below is the email i received.

A New Lead Has been Referred By a Sales Representative. For AccountBurlington Textiles Corp of America Requirement of null Lead Number00Q28000001qnBWEAY records were not updated successfully.

Also please let me know your gchat id's would like to connect with you guys.
viruSviruS
Hi Kiran,

Try 

Email body with in 
<HTML><a href="'+URL.getSalesforceBaseUrl()+'/'+EmailLead.ID+'">'+EmailLead.name+'</a></HTML>

Add Name to Soql 
Kiran MarketingKiran Marketing
Viru

Tried to get that HTML tag in the trigger code but not able to. Is there any APEX code to get such tag.

I am sorry these are my early stages of APEX. I am a functional consultant. Can you also please provide me with you gchat id or some chat id where we can connect more offend and see if we can work together.
viruSviruS
give me your id gmail or skypeId ..
SaranSaran
Hi Kiran,

You have add an additional line in your class.

Your class will be like.
 
public class LeadTriggerHelperClass1 {

    public static void isBeforeInsert(List<Lead> LeadList){
	    
	    id recTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('R    ecord_Type_Name').getRecordTypeId();

// instead of hardcoding the recordtypeID you can get it like this. Replace Record_Type_name with your record type name 

	    for(Lead Lea :LeadList){ 
	        If(Lea.RecordTypeid == recTypeId){
	              Lea.OwnerId = Lea.Reffered_To__c;
	        }
	    }
	}
    
    public static void isAfterInsert(set<id> LeadId){
    

        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        
        for(Lead EmailLead :[SELECT id,Company, Description, createdBy.email FROM Lead WHERE id in :LeadId]){
                 String emailMessage ='A New Lead '
                     +'Has been Referred '
                     +'By a Sales Representative.' 
                     +' For Account'+ EmailLead.Company 
                     +' Requirement of ' 
                     + EmailLead.Description +
                     ' Lead Number'
                     + EmailLead.ID 
                     +' records were not updated successfully.';
                     
                 String baseUrl = System.URL.getSalesforceBaseUrl().toExternalForm();
                 
                 emailMessage = emailMessage + '<a href="'+baseUrl+'/'+EmailLead.id +'">'+EmailLead.id+'</a>';
                 
                Messaging.SingleEmailMessage mail =    new Messaging.SingleEmailMessage();
               String[] toAddresses =new String[] {EmailLead.createdBy.email};
                mail.setToAddresses(toAddresses);
                mail.setReplyTo('noreply@salesforce.com');
                mail.setSenderDisplayName('Lead Created');
                mail.setSubject('Lead Created');
             //   mail.setPlainTextBody(emailMessage);
                mail.setHtmlBody(emailMessage);
                mails.add(mail);
        }
    
        Messaging.sendEmail(mails);
    }
}

Hope this might solve your issue.

Thanks
This was selected as the best answer
Kiran MarketingKiran Marketing
Viru / Saran

Thanks so so much. This was very very helpful. My gmail id is kiranmarketing16@gmail.com

Please do add me and send me your chat ids.