• Mykola Odnoshyvkin
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies

Hallo,
i am new in apex and i am trying to make a trigger for lead that automatically converts Leads with custom field LeadSource__c ='WebFormToTest' to an account if it doesnt exist and add a contact to this account. The lead i get from WebToLead Form. Some how my code doesnt work. Can you help me?

Code
LeadSource is just text field.
Trigger:

trigger NewLeadToContact on Lead (before insert) {
    
    List<Lead> leads=new List<Lead>();
    
    for(Lead newLead:Trigger.new){
		leads.add(newLead);
	}
  
	System.debug(LeanToContactHelpClass.createContactFromLead(leads));
}
HelpClass:
public class LeanToContactHelpClass {
	public static Boolean createContactFromLead(List<Lead> tempLeadList){
		List<Contact> contacts=new List<Contact>();
		for(Lead tempLead:tempLeadList){
			String str= String.ValueOf(lead.LeadSource__c);
			//== is used because it is case insensetive
		if(str.equals('WebFormToTest')){
			Account newAccount=null;
			try{
				//Can be thrown a QueryException when query returns not only one object
				newAccount = [Select name,id from Account  where Name=:tempLead.Company];
			
				System.debug('Account with needed Company name was found');
				
				//Create new contact associated with this account
				contacts.add(createContactFromAccountId(newAccount.id,tempLead));
					
			}catch(QueryException e){
				System.debug('Duplicates or Nothing found. Many Accounts for one Company found.');
				
				//If account doesnt exist we create a new one
				System.debug('Account with name '+lead.Company+' does not exist.');
				newAccount=createAccountFromLead(tempLead);
				
				insert newAccount;
				
				System.debug('New account was created');
				
				//Create new contact associated with this account
				contacts.add(createContactFromAccountId(newAccount.id,tempLead));
			}
		}
	}
	try{
		Database.insert(contacts);
		return true;
	}catch (Exception e) {
      return false;
	}
}
	
	private static Contact createContactFromAccountId(String accountId,Lead tempLead){
		//AccountId is used for connection this contact to an account
		System.debug('New contact will be created');
		Contact newContact= new Contact(
					FirstName = tempLead.firstname,
					LastName = tempLead.lastname,
					AccountId = accountId,
					Email = tempLead.email,
					Title = tempLead.title,
					Phone = tempLead.Phone);
		return newContact;			
	}
	
	private static Account createAccountFromLead(Lead tempLead){
		System.debug('New account will be created');
		Account newAccount = new Account(Name=String.ValueOf(lead.company));
		
		return newAccount;
	}
}