function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vignesh RamshettyVignesh Ramshetty 

No changes in account record with below code

If I insert contact record the related account record employees number should be updated below is the code able to save but  account record is not updating in account record.


public class contactclass2 {

public static void makefunction(List<Contact> varcon){
 
set<string> varset = new set<string>();


for(contact con :varcon ){

         if(con.Accountid != null){

              varset.add(con.Accountid);
      }

    }
if(varset.size() > 0){
list<Account> varacc = new list<Account>();


varacc = [SELECT id,Name,Fax,NumberOfEmployees,(Select id From contacts) FROM ACCOUNT WHERE id in: varacc];

if(varacc.size() > 0 ){

for(Account a : varacc){

      
             a.NumberOfEmployees  = a.contacts.size();

            varacc.add(a);
   }

update varacc;

 }
 }
 }

}


trigger Uff on Contact (after insert) {

   contactclass2.makefunction(trigger.new);

}
PriyaPriya (Salesforce Developers) 
Hey Vignesh,

Your SOQL querry seems to be wrong. 

You have written :-
varacc = [SELECT id,Name,Fax,NumberOfEmployees,(Select id From contacts) FROM ACCOUNT WHERE id in: varacc];

in above, both the variable are same.

replace the query with below :-
varacc = [SELECT id,Name,Fax,NumberOfEmployees,(Select id From contacts) FROM ACCOUNT WHERE id in: varset];

Note:- Always use system.debug statement to test the value.

Please close the thread by selected as Best Answer so that we can keep our community clean

Thanks & Regards,

Priya Ranjan