You need to sign in to do that
Don't have an account?
Sambit Sorav
Create an account with name 'test account' & create a field on account - > number of contacts. Write a trigger such that when whenever a new contact is created it is automatically added to 'test account'.
Hi,
Create an account with name 'test account' & create a field on account - > number of contacts. Write a trigger such that when whenever a new contact is created it is automatically added to 'test account'.
Please help me writing this trigger. I have written the following code. Pls tell me where am I going wrong.
Thanks
trigger InsertContact1 on Contact (after insert) {
Account acList = [Select id, Name from Account where Name = 'Test Account'];
List<Contact> contList = new List<contact>();
for(Contact c: trigger.new){
contList.add(c);
} insert contList;
if(contList.size()>0){
for(Contact c: contList){
c.AccountId = acList.id;
acList.Number_Of_Contacts__c = integer.valueOf(contList.size());
}
}
}
Create an account with name 'test account' & create a field on account - > number of contacts. Write a trigger such that when whenever a new contact is created it is automatically added to 'test account'.
Please help me writing this trigger. I have written the following code. Pls tell me where am I going wrong.
Thanks
trigger InsertContact1 on Contact (after insert) {
Account acList = [Select id, Name from Account where Name = 'Test Account'];
List<Contact> contList = new List<contact>();
for(Contact c: trigger.new){
contList.add(c);
} insert contList;
if(contList.size()>0){
for(Contact c: contList){
c.AccountId = acList.id;
acList.Number_Of_Contacts__c = integer.valueOf(contList.size());
}
}
}
This can be done with before insert trigger
1, need not to insert contact again, inside contact trigger, that will create recursion.
2, You are trying to update the number of contacts field inside for loop, which will show only the contacts inserted at that point of time. it will not sum up the total number of contacts for that account.
you can try this below code. Thanks
Surya G
All Answers
Try Below Code Please Mark It As Best Answer If It Helps
Thank You!
This can be done with before insert trigger
1, need not to insert contact again, inside contact trigger, that will create recursion.
2, You are trying to update the number of contacts field inside for loop, which will show only the contacts inserted at that point of time. it will not sum up the total number of contacts for that account.
you can try this below code. Thanks
Surya G
Hi,
Try this below code. You have not query the Number_Of_Contacts__c it will give you error.
Please mark it as the Best Answer if it helps you
Thank You