+ Start a Discussion
Chris MarzellaChris Marzella 

Contact not relating to account

I am trying to create a new contact upon creation of a new account, which works, but it is not relating to the new account, It relates to another account in my dev org. Why is this? I am sure this is something simple enough. I am new to apex and testing out some basic code.
 
trigger CreateContact on Account (after insert) {
    
    for(Account acc : Trigger.new){
        Contact c = new Contact();
        c.FirstName = 'John';
        c.LastName = 'Lock';
        c.AccountId = acc.Id;
        
        insert c;
    }

}

 
Best Answer chosen by Chris Marzella
Vishal_GuptaVishal_Gupta
Hi Chris,

Is there any trigger written on Contact insertion, that might causing the issue?

Can you please let us know the record type of Account, is it Person record type? In case of person account, contact created itself there is no need to add code for contact creation.

Please verify above points.

Thanks,
Vishal

All Answers

William TranWilliam Tran

Since you have many contacts with the same name, why don't you do this to confirm:
 
trigger CreateContact on Account (after insert) {
    
    for(Account acc : Trigger.new){
        Contact c = new Contact();
        c.FirstName = 'John - ' + acc.Name;
        c.LastName = 'Lock - ' +acc.Name;
        c.AccountId = acc.Id;
        
        insert c;
    }

}

Thx
Chris MarzellaChris Marzella
That appended the correct account name to the contact's first and last names, but it still doesn't get the contact assigned to the newly created account.
Vishal_GuptaVishal_Gupta
Hi Chris,

Is there any trigger written on Contact insertion, that might causing the issue?

Can you please let us know the record type of Account, is it Person record type? In case of person account, contact created itself there is no need to add code for contact creation.

Please verify above points.

Thanks,
Vishal
This was selected as the best answer
Chris MarzellaChris Marzella
Vishal,

You're a genius! lol. I can't believe I didn't check that. Thanks!
Vishal_GuptaVishal_Gupta
Hi Chris,

Thanks for appreciation, please change the trigger to keep DML operation outside of for loop to ignore the governor limit issue :

trigger CreateContact on Account (after insert)
{
List<Contact> lstContact = new List<<Conatct>();
for(Account acc : Trigger.new)
{
     Contact c = new Contact();
     c.FirstName = 'John';
     c.LastName = 'Lock';
     c.AccountId = acc.Id;
     lstContact.add(c) ;
}
insert lstContact
}

Thanks,
Vishal