You need to sign in to do that
Don't have an account?

Update Account when a Contact is created
Idea - When a contact is created, check if the associated account's primary_contact_sfid__c field is filled or not. If it is empty, put the contact's id in there. When I test the code, there is a stem assetion failure. Please advise. Thanks!
trigger updateacc on Contact (after insert) {
List<ID> accountids = New List<ID>();
for(Contact c : trigger.new){
if(c.Accountid != null){
accountids.add(c.AccountId);
}
}
List<Account> acclist = [SELECT ID, Primary_Contact_SFID__C FROM Account WHERE ID IN: accountids];
List<Account> updateacc = New List<Account>();
for(Contact c : trigger.new){
for(Account acc: acclist){
if(c.AccountId ==acc.id && c.Account.Primary_Contact_SFID__c == null){
acc.Primary_Contact_SFID__c =''+c.id;
updateacc.add(acc);
}
}
}
update (updateacc);
}
trigger updateacc on Contact (after insert) {
List<ID> accountids = New List<ID>();
for(Contact c : trigger.new){
if(c.Accountid != null){
accountids.add(c.AccountId);
}
}
List<Account> acclist = [SELECT ID, Primary_Contact_SFID__C FROM Account WHERE ID IN: accountids];
List<Account> updateacc = New List<Account>();
for(Contact c : trigger.new){
for(Account acc: acclist){
if(c.AccountId ==acc.id && c.Account.Primary_Contact_SFID__c == null){
acc.Primary_Contact_SFID__c =''+c.id;
updateacc.add(acc);
}
}
}
update (updateacc);
}
Try with below code it wil help !! Let me know if it helps !!
Thanks
Manoj
Thanks for your quick response. Unfortunately, when I ran the test class, it throws a system assertion error which means the rigger is not updating the record.
@istest
public class testmerch {
static testMethod void validatemerch() {
Account a = New Account();
a.Name ='BW';
a.Primary_Contact_SFID__c ='';
a.Management__c = 'Independent';
Insert a;
Account b = New Account();
b.Name ='BW2';
b.Management__c = 'Independent';
b.Primary_Contact_SFID__c ='';
Insert b;
Contact con = New Contact();
con.LastName = 'test';
con.Account = a;
Insert con;
system.assertequals(a.Primary_Contact_SFID__c, con.id+'');
Contact con2 = New Contact();
con2.LastName = 'test2';
con.Account = a;
Insert con2;
system.assertequals(a.Primary_Contact_SFID__C, con.id+'');
}
}
Thanks!
Modify your code as below it will work .
Test class Basically In contact the account relationship name is AccountId and we ahould assign account variable .Id to it .
Let me know if it helps !!
Thanks
Manoj