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

I am trying to count the number of contacts associated with the account
Iam trying to count the number of contacts on account, Iam getting the following error message
Error: Compile Error: Initial term of field expression must be a concrete SObject: LIST<Account> at line 10 column 1
Trigger counting on contact(after update,after insert){
Set<account> accids=New Set<Account>();
For(contact c:trigger.new){
Accids.add(c.Account);
}
List<Contact> con = [select id from contact where AccountID IN:accids];
List<Account> Acc=[Select count__C from account where id IN:accids ];
For(contact c:trigger.new)
{
Acc.count__c=con.size();
}
}
Set<Id> aId = new Set<Id>();
if(Trigger.isInsert){
for(Contact opp : Trigger.New){
aId.add(opp.AccountId);
}
List<Account> acc = [select id,count_of_contacts__c from Account where Id in:aId];
List<Contact> con = [select id from contact where AccountId in :aId];
for(Account a : acc){
a.count_of_contacts__c=con.size();
}
update acc;
}
if(Trigger.isDelete){
for(Contact opp : Trigger.old){
aId.add(opp.AccountId);
}
List<Account> acc = [select id,count_of_contacts__c from Account where Id in:aId];
List<Contact> con = [select id from contact where AccountId in :aId];
for(Account a : acc){
a.count_of_contacts__c=con.size();
}
update acc;
}
is that the trigger will not work in bulk. If you do a dataload or DML statement with multiple records on contacts, the contact list size will be the size of both accounts combined. You have to separate the list to make sure you are getting a true count of contacts per account.
I tried with your code, fo rsome reason, it doesn't work, code gets saved though.
try this one. I had a couple of errors
I have tried with your code, still Iam getting the error message
Error: Compile Error: unexpected token: 'from' at line 7 column 45
Still the same, it doesn't count contacts,but code gets saved.
Did you get this working?
@isTest
private class testContactCount {
static testMethod void testContactCount() {
Account acc = new Account(Name = 'Testy Account');
insert acc;
Contact con = new Contact (LastName = 'Test Contact', AccountId = acc.Id);
insert con;
acc = [Select Id, Name, TotContacts__c from Account where Id = :acc.Id];
System.assertEquals(1, acc.TotContacts__c);
}
}
Use this test class:
This test covers more scenarios.
Yes, you should deploy this along with the trigger.
Thanks