0

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?

if(Trigger.isInsert){
    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);
            accountList.add(account);

            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
            );
            contactList.add(contact);    
        }
    }
    if(accountList.size() > 0 && contactList.size() > 0){      
        insert accountList;    
        insert contactList; 
    }
}

1 Answer 1

0

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') {
    ownerIds.add(record.OwnerId);
    leadsToConvert.add(record);
  }
}

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) {
  newAccounts.add(
    new Account(
      Name=record.Company,
      cnpj__c=record.cnpj__c
    )
  );
}
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);
  newContacts.add(
    new Contact(
      FirstName=owner.FirstName,
      LastName=owner.LastName,
      Email=owner.Email,
      Phone=owner.Phone,
      AccountId=newAccounts.remove(0).Id
    )
  );
}
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.