+ Start a Discussion
DDSDDS 

Trigger to Auto-Create individual Account error: INVALID_FIELD_FOR_INSERT_UPDATE

Hi guys,

 

I'm a beginner apex coder and I just wrote a small trigger to automatically create an account when you don't assign one to a new contact. It basically creates an individual account with the same name as the contact and then associates that account to the contact. Here's the code:

 

 

trigger CreateIndividualAccount on Contact (before insert, before update) {
Account[] acc = new Account[0];
RecordType arec = [SELECT ID from RecordType WHERE SobjectType='Account' AND Name='Individual' limit 1];
for (Contact c : trigger.new)
{
if(c.AccountID == null)
{
string cName = (c.FirstName + ' ' + c.LastName);
acc.add(new Account (Name = cName, RecordTypeId = arec.Id));

insert acc;
c.AccountID = acc[0].Id;
}
}
}

 

I tried importing contacts in my dev org and it works fine, but when I do it in production under a managed package it returns the error " INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call "

 

Does anyone know what I'm doing wrong? Again, these are some of the first lines of code I've ever written so it might be pretty obvious.

 

Thanks in advance.

 

 

Note: The account record type "Individual" does exist and is part of the managed package. Would i have to add the namespace prefix to the record type name?

 

Best Answer chosen by Admin (Salesforce Developers) 
rocwilcoxrocwilcox

You can set the RecordTypeID on insert (and should) you cannot set the ID.

Your trigger can process more than one record, I assume that you are updating or inserting more than one contact.

The 2nd time though the loop the acc record already exists and you are trying to insert it again.

 

Move this "new" account line to inside the for loop over the trigger.new (inside the If c.AccountID == null even, no need to make one you are not going to use) to make a new account for each contact in this contiion

 Account[] acc = new Account[0];

 

All Answers

rocwilcoxrocwilcox

You can set the RecordTypeID on insert (and should) you cannot set the ID.

Your trigger can process more than one record, I assume that you are updating or inserting more than one contact.

The 2nd time though the loop the acc record already exists and you are trying to insert it again.

 

Move this "new" account line to inside the for loop over the trigger.new (inside the If c.AccountID == null even, no need to make one you are not going to use) to make a new account for each contact in this contiion

 Account[] acc = new Account[0];

 

This was selected as the best answer
DDSDDS

Worked like a charm!!

 

Thanks a lot roc!

 

Happy Holidays!