I'm trying to update the account every time a contact is updated and the simplest thing seems to be blowing up.
trigger ContactAccountOriginTrigger on Contact (before insert, before Update) {
List<Account> AccountList = new List<Account>();
List<ID> IdList = new List<ID>();
for (Integer i = 0; i <Trigger.new.size(); i++){
IdList.Add(Trigger.new[i].AccountId);
}
AccountList = [SELECT Id, Name FROM Account WHERE Id in : IdList];
for (Integer i = 0; i <Trigger.new.size(); i++){
if (AccountList.size() > 0){
for (Account a:AccountList){
if(Trigger.new[i].Focus_ID__c != null || Trigger.new[i].Focus_ID__c == ''){
logic
}
else{
logic
}
if(a.get('Id') == null) {
insert a;
}else{
update a;
}
}
}
}
}
Test Class
@isTest
public class ContactAccountOriginTest {
static testMethod void insertNewAccount() {
Account acctToCreate = new Account();
Contact contToCreate = new Contact();
acctToCreate.Name = 'Practice Test';
insert acctToCreate;
//1st pass
contToCreate.FirstName = 'test';
contToCreate.LastName = 'test';
contToCreate.AccountId = acctToCreate.Id;
contToCreate.Focus_ID__c = '00001';
insert contToCreate;
update acctToCreate;
//2nd pass
contToCreate.FirstName = 'test';
contToCreate.LastName = 'test';
contToCreate.AccountId = acctToCreate.Id;
contToCreate.Focus_ID__c = null;
update contToCreate;
update acctToCreate;
}
}
upsert
to say to the database "hey, update this thing if it exists, or insert it otherwise". So you can eliminate that last condition when you check the Id.