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
Anil Kumar 1257Anil Kumar 1257 

Apex trigger to update contact stage when the intervew stage equals chedule

trigger updatestageoncontact on Interview__c(after insert, after update){
 list<Id> contIds = new list<Id>();
 list<Contact> Contacts = new list<Contact>();
 for(Interview__c inte:trigger.new){
  contIds.add(inte.Candidate__c);
 }
 for(contact con:[select Id, Stage__c from contact where Id IN :contIds]){
  for(Interview__c inter:trigger.new){
   if(inter.Status__c=='Scheduled'){
    con.Stage__c='Interview Scheduled';
    Contacts.add(con);
   }
  }
 }
    update contacts;
}


How to write test class this trigger
tbrookstbrooks
Hey Anil,
One suggestion I might make is to modify trigger to such, just add in the check for if the interview status is scheduled to add that contact Id, just so you don't run through trigger.new twice. Just a best practice.
 
trigger updatestageoncontact on Interview__c(after insert, after update){
 list<Id> contIds = new list<Id>();
 list<Contact> Contacts = new list<Contact>();
 for(Interview__c inte:trigger.new){
  if(inte.Status__c=='Scheduled'){
    contIds.add(inte.Candidate__c);
  }
 }
 if(!contIds.isEmpty()){
  for(contact con:[select Id, Stage__c from contact where Id IN :contIds]){
    con.Stage__c='Interview Scheduled';
    Contacts.add(con);
  }
    update contacts;
 }
}

And here would be the test class
 
@IsTest
private without sharing class testupdatestageoncontact {

   @TestSetup
   static void makeData() {
       Account acc = new Account(Name = 'Test Acc');
       Insert Acc;
       Contact con = new Contact(FirstName = 'Test', LastName = 'Contact', AccountId = 
       acc.Id);
       Insert con;
       //Put in whatever status is accepted that isn't Scheduled
       Interview__c int = new Interview__c(Status__c = 'Pending', Candidate__c = con.Id);
       Insert int; 
   }
   @isTest
    static void testupdateStage() {
       Interview Int = [SELECT Id, Status__c FROM Interview__c WHERE Status__c = 
      'Pending' LIMIT 1];
      Test.startTest();
      Int.Status__c = 'Scheduled';
      update Int;
      Test.stopTest();
      System.assertEquals(1, [SELECT Count() FROM Contact WHERE Stage__c = 
      'Interview Scheduled']);
    }

Please let me know if this resolves your issue and mark as best answer if it does!
Regards,
Tyler