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
RohanSharma8791RohanSharma8791 

Write a trigger on insert and update to show an error to the user when the total number of hours for a specific date is greater then 24

  1. Create a new object Time Tracking with the following fields:
Name
Hours(Decimal)
Date(Date)
Description(Text)
User(Lookup)

Write a trigger on insert and update to show an error to the user when the total number of hours for a specific date is greater than 24.
 
Best Answer chosen by RohanSharma8791
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Karan

The trigger logic can be like below.
 
trigger LogicTrigger on Time_Tracking__c (before insert,before update) {
    Date datefield;
    Date fatefield2;
    
    for(Time_Tracking__c time1:Trigger.new){
       datefield=time1.Date__c; 
    }
AggregateResult[] groupedResults= [select Sum(Hours__c) sumofhours,Date__c from Time_Tracking__c where Date__c =:datefield group by Date__c];
    
    for(Time_Tracking__c tr2:Trigger.new){
        if(groupedResults.size()>0){
 Decimal hours=((decimal)groupedResults[0].get('sumofhours'));
        if(hours+tr2.Hours__c>24){
            tr2.addError('hours cannot exceed 24');
        }
        }
    }
}

If this solution helps, Please mark it as best asnwer.

Thanks,

 

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Karan

The trigger logic can be like below.
 
trigger LogicTrigger on Time_Tracking__c (before insert,before update) {
    Date datefield;
    Date fatefield2;
    
    for(Time_Tracking__c time1:Trigger.new){
       datefield=time1.Date__c; 
    }
AggregateResult[] groupedResults= [select Sum(Hours__c) sumofhours,Date__c from Time_Tracking__c where Date__c =:datefield group by Date__c];
    
    for(Time_Tracking__c tr2:Trigger.new){
        if(groupedResults.size()>0){
 Decimal hours=((decimal)groupedResults[0].get('sumofhours'));
        if(hours+tr2.Hours__c>24){
            tr2.addError('hours cannot exceed 24');
        }
        }
    }
}

If this solution helps, Please mark it as best asnwer.

Thanks,

 
This was selected as the best answer
RohanSharma8791RohanSharma8791
it worked for me, but i also have a condition that like there are many users in an org and every user have different time records so, i also have to check the condition that all the records of users are less then 24 hours.
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Karan,

You mean that it should group by user and date?. If so can you create an another question for the same. As it would be followup question.

Thanks,