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
Gerald HarmensGerald Harmens 

Cross Object Date Field Apex Trigger

Hello,

I have the trigger below that is NOT giving me any errors but it is not working. I need to update field Prospect.Demo_Not_Sold_Date__c with Appointment.i360__Result__c IF Appointment.i360__Result__c == 'Demoed, Not Sold'
trigger Appointment_DNS_Date on i360__Appointment__c (after insert) 
{
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert)
        {
            set<Id> ProspectSet = new set<Id>();
            for(i360__Appointment__c Appointment :Trigger.new){
                ProspectSet.add(Appointment.i360__Prospect__c);
            }
            map<string, i360__Prospect__c> ProspectMap = new map<string, i360__Prospect__c>(
                [SELECT Id, Demo_Not_Sold_Date__c FROM i360__Prospect__c WHERE Id IN :ProspectSet]
            );
            list<i360__Prospect__c> ProspectsToUpdate = new list<i360__Prospect__c>();
            for(i360__Appointment__c appointment : Trigger.new){
                i360__Prospect__c prospect = new i360__Prospect__c();
                Prospect.Id = ProspectMap.get(Appointment.i360__Prospect__c).Id;
                if(Appointment.i360__Result__c == 'Demoed, Not Sold'){
                    prospect.Demo_Not_Sold_Date__c = appointment.Result_Date__c;
               
                }
                ProspectsToUpdate.add(prospect);
            }
            if(ProspectsToUpdate.size() > 0){
                update ProspectsToUpdate;
            }
        }
    }
}

 
Amit Chaudhary 8Amit Chaudhary 8
Please update your code like below
trigger Appointment_DNS_Date on i360__Appointment__c (after insert) 
{
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert)
        {
            set<Id> ProspectSet = new set<Id>();
            for(i360__Appointment__c Appointment :Trigger.new)
			{
                ProspectSet.add(Appointment.i360__Prospect__c);
            }
			
            map<string, i360__Prospect__c> ProspectMap = new map<string, i360__Prospect__c>(
                [SELECT Id, Demo_Not_Sold_Date__c FROM i360__Prospect__c WHERE Id IN :ProspectSet]
            );
			
            list<i360__Prospect__c> ProspectsToUpdate = new list<i360__Prospect__c>();
            
			for(i360__Appointment__c appointment : Trigger.new)
			{
                if(appointment.i360__Result__c == 'Demoed, Not Sold' && ProspectMap.containsKey(appointment.i360__Prospect__c) )
				{
					i360__Prospect__c prospect = ProspectMap.get(appointment.i360__Prospect__c);
					prospect.Demo_Not_Sold_Date__c = appointment.Result_Date__c;
					ProspectsToUpdate.add(prospect);
                }
            }
			
            if(ProspectsToUpdate.size() > 0)
			{
                update ProspectsToUpdate;
            }
        }
    }
}

Let us know if this will help you