I'm trying to create a trigger that creates an account and contact when the lead status is changed to a given value. The contact value needs to come from the Lead Owner User. How can I achieve that?

    List<Account> accountList = new List<Account>();
    List<Contact> contactList = new List<Contact>();
    List<User> leadOwner = new List<User>();

    for (Lead lead : Trigger.new) {
        System.debug('lead: ' + lead);

        if(lead.Status == 'Confirmed Contact'){
            Account account = new Account(Name = lead.Company, cnpj__c = lead.cnpj__c);

            Contact contact = new Contact(
                FirstName = //need information from the owner lead
                LastName = //need information from the owner lead
                Email = //need information from the owner lead
                Phone = //need information from the owner lead
                AccountId = account.Id
    if(accountList.size() > 0 && contactList.size() > 0){      
        insert accountList;    
        insert contactList; 

1 Answer 1


You can write that something like this.

First, we'll initialize some variables.

Set<Id> ownerIds = new Set<Id>();
Account[] newAccounts = new Account[0];
Contact[] newContacts = new Contact[0];
Lead[] leadsToConvert = new Lead[0];

Then, we'll find all records that have their status set to Confirmed Contact.

for(Lead record: Trigger.new) {
  if(record.Status == 'Confirmed Contact') {

Next, we need the owner's details for later.

Map<Id, User> owners = new Map<Id, User>([
  SELECT FirstName, LastName, Email, Phone
  FROM User WHERE Id = :ownerIds

And now we'll create the Account records.

for(Lead record: leadsToConvert) {
    new Account(
insert newAccounts;

Note that we have to insert the accounts before we can use the Account Id. Now, we create the contacts using the owner information.

for(Lead record: leadsToConvert) {
  User owner = owners.get(record.OwnerId);
    new Contact(
insert newContacts;

The last trick, newAccounts.remove(0).Id works because the accounts were added in the same order as the contacts, so we can use newAccounts as a FIFO (first in, first out) buffer.

This code doesn't address things like Queues or any real error handling. You will most likely need to make changes to the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.