Skip to main content
I am using a Marketing Automation Tool that will Create a Contact (not using Leads), I created a trigger to create Account (FirstName LastName and - Account, I get error and trigger and test class below:

Error Message System.ListException: List index out of bounds: 0

Stack Trace Class.CreateAccountFromContact_UnitTest.runTest: line 14, column 1

trigger CreateAccountFromContact on Contact (before insert) {

//Collect list of contacts being inserted without an account

    List<Contact> needAccounts = new List<Contact>();

    for (Contact c : trigger.new) {

        if (String.isBlank(c.accountid)) {

            needAccounts.add(c);

        }

    }

   

    if (needAccounts.size() > 0) {

        List<Account> newAccounts = new List<Account>();

        Map<String,Contact> contactsByNameKeys = new Map<String,Contact>();

        //Create account for each contact

        for (Contact c : needAccounts) {

            String accountName = c.firstname + ' ' + c.lastname + ' ' + ' - Account ';

            contactsByNameKeys.put(accountName,c);

            Account a = new Account(name=accountName);

            newAccounts.add(a);

        }

        insert newAccounts;

       

              

  }     

}

 

@isTest

public with sharing class CreateAccountFromContact_UnitTest {

    @isTest

    public static void runTest(){

        String firstname = 'first';

        String lastname = 'last';

               

        //Create contact

        Contact c = new Contact(firstname=firstname, lastname=lastname);

        insert c;

        

        //Verify account

        c = [select id, accountid, firstname, lastname from Contact where id =:c.Id][0];

        Account a = [select id, name from Account where id = :c.accountId][0];

        

        system.assertEquals(firstname + ' ' + lastname + ' ' + ' - Account ', a.name);

        

        

    }

}
9 Antworten
  1. 4. März 2015, 16:05

    You forgot to add this logic in trigger:

    trigger CreateAccountFromContact on Contact (before insert) {

    //Collect list of contacts being inserted without an account

    List<Contact> needAccounts = new List<Contact>();

    for (Contact c : trigger.new) {

    if (String.isBlank(c.accountid)) {

    needAccounts.add(c);

    }

    }

    if (needAccounts.size() > 0) {

    List<Account> newAccounts = new List<Account>();

    Map<String,Contact> contactsByNameKeys = new Map<String,Contact>();

    //Create account for each contact

    for (Contact c : needAccounts) {

    String accountName = c.firstname + ' ' + c.lastname + ' ' + ' - Account ';

    contactsByNameKeys.put(accountName,c);

    Account a = new Account(name=accountName);

    newAccounts.add(a);

    }

    insert newAccounts;

    for(Account acc :newAccounts){

    contactsByNameKeys.get(acc.Name).AccountId = acc.Id;

    }

    }

    }