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
ForceRookieForceRookie 

How to set task Due Date in Apex Trigger?

I have this Custom Task object.. Help me to calculate the Due Date based on Dependency’s Days After value.

This is the example..
this is manual insert and it automatically create a Due Date.
and it’s complicated to do programmatically.User-added image
Vinod Chokkula 3Vinod Chokkula 3
You can use a formula field to calculate DueDate. Try this
 DATEVALUE($System.OriginDateTime) + days_after__c


 
ForceRookieForceRookie
Hi Vinod, I need apex trigger. :(
Adilson Arcoverde JrAdilson Arcoverde Jr
Hi ForceRookie,

Try this code:
 
trigger TaskTrigger on Task__c (before insert, before update) {
	
	if( Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) {
		Set<String> dependenciesId = new Set<String>();
		
		for(Task__c t : Trigger.new) {
			if(t.Dependency__c != null) {
				dependenciesId.add(t.Dependency__c);
			}
		}

		Map<String,Task__c> dependenciesMap = new Map<String,Task__c>();
		for(Task__c dependency : [Select Id, Days_Before_Or_After__c, Due_Date__c from Task__c where Id in :dependenciesId]) {
			dependenciesMap.put(dependency.Id, dependency);
		}
		
		for(Task__c t : Trigger.new) {
			Task dependency = dependenciesMap.get(t.Dependency__c);
			if(dependency != null) {
				t.Due_Date__c = dependency.Due_Date__c.addDays(dependency.Days_Before_Or_After__c);
			}
		}
	}
}

I hope you find this solution helpful. If it does, pleas mark as Best Answer to help others too.

Regards.