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
harish reddy 39harish reddy 39 

Trigger to update value on one master object based on other master object .

I have two master objects ( positions__c ,Candidates__c) and junction object jobapplications__C ,now there is field on positions__C called noofcandidates__c which should be updated with no of  candidates for each position.
I have tried it my functionality not working can some help me.

Code:

trigger noofcandidatestrigger1 on Candidates__c (After insert,After Update,After Delete)
{    List<id> Ids = New List<id>();
     List<positions__c> pos1 = new List<positions__c>();
    If(Trigger.IsInsert)
    {
     for(Candidates__c con: Trigger.New)
     {
          Ids.add(con.id);   
     }
    }
 
     If(Trigger.IsUpdate || Trigger.IsDelete)
     {
        for(Candidates__c con: Trigger.old)
        {
            Ids.add(con.id);
        }
     }
 List<positions__c> pos = [Select id,Noofcandidates__c from positions__c where id in: ids];
 List<Job_Applications__c> job = [Select id,Status__c from Job_Applications__c where id in :ids];
 
 for(positions__c positi : pos)     
   {
     positi.Noofcandidates__c = job.size(); 
       pos1.add(positi);
   }
    update pos1;
}
harish reddy 39harish reddy 39
For same scenario i have written code using map eve now its not working.

Code:

trigger  noofcandidatestrigger1ver2 on Candidates__c (after update) {

   List<id> ids = New List<id>();
   
   for(Candidates__c  con : Trigger.new)
   {
        ids.add(con.id);
   }
   
   Map<ID,positions__c>  posmapids = New Map<ID,positions__c>([Select id,Noofcandidates__c ,(Select id from Job_Applications__r) from positions__c where id in : ids ]);

     Integer count = 0;
    
    For(ID mapids :posmapids.KeySet() )
    {
    
        For(Job_Applications__c job :posmapids.get(mapids).Job_Applications__r)
        {
          count++ ;          
        }
    
        posmapids.get(mapids).Noofcandidates__c = count;
    
    }
       update posmapids.values();

}