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
Sean ClarkSean Clark 

Apex Trigger to create a task on MVP object (Only Create on a weekday)

I have created a Apex Trigger to create a task on the MVP object when the Last Contacted On date is 30 days old.

Is there anyway i can make it so that the task will only be created on a weekday? (Monday - Friday)



trigger OldMVPTrigger on MVP__c (after insert) {
    
    List<Task> taskListToInsert = new List<task>();
    
    for(MVP__c mvp:Trigger.new)
    {
        if(mvp.Last_Contacted_On__c == Date.Today().addDays(-30)) 
        {
           task t = new Task();
           t.Subject = 'Call [MVP__c].MVP__c.FirstName Today';
           t.OwnerId = '[MVP__c].MVP_Owner__c';
           t.WhatId = mvp.Id;
           taskListToInsert.add(t);
        }
    }
    if(taskListToInsert.size() > 0)
    {
        insert taskListToInsert;
    }
}
Best Answer chosen by Sean Clark
Nishant Prajapati 10Nishant Prajapati 10
Hi Sean 
Please try following code.
trigger OldMVPTrigger on MVP__c (after insert) {
    
    List<Task> taskListToInsert = new List<task>();
    
    for(MVP__c mvp:Trigger.new)
    {
        if(mvp.Last_Contacted_On__c == Date.Today().addDays(-30) && system.today() <=    system.today().toStartOfWeek().addDays(5) ) 
        {
           task t = new Task();
           t.Subject = 'Call [MVP__c].MVP__c.FirstName Today';
           t.OwnerId = '[MVP__c].MVP_Owner__c';
           t.WhatId = mvp.Id;
           taskListToInsert.add(t);
        }
    }
    if(taskListToInsert.size() > 0)
    {
        insert taskListToInsert;
    }
}

All Answers

Nishant Prajapati 10Nishant Prajapati 10
Hi Sean 
Please try following code.
trigger OldMVPTrigger on MVP__c (after insert) {
    
    List<Task> taskListToInsert = new List<task>();
    
    for(MVP__c mvp:Trigger.new)
    {
        if(mvp.Last_Contacted_On__c == Date.Today().addDays(-30) && system.today() <=    system.today().toStartOfWeek().addDays(5) ) 
        {
           task t = new Task();
           t.Subject = 'Call [MVP__c].MVP__c.FirstName Today';
           t.OwnerId = '[MVP__c].MVP_Owner__c';
           t.WhatId = mvp.Id;
           taskListToInsert.add(t);
        }
    }
    if(taskListToInsert.size() > 0)
    {
        insert taskListToInsert;
    }
}
This was selected as the best answer
Sean ClarkSean Clark
Hello Nishant,

Thank you for this!