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
kuttibarani1.3897618179833977E12kuttibarani1.3897618179833977E12 

Comparing new record with old records in custom object

Hi,

I have an object and everytime when I add new record, it should compare the new value with all of it's earlier values from the object.

For example, there is a date field in my custom object and everytime when I a new record it should validate me such a way that the recent record's date field should be greater than all of it's earlier records.  How can I do that.

Kindly explain me in detail.

Thanks
G. Barani
m.elmoussaouim.elmoussaoui
Hello,

I think you can achive this by creating a trigger on your object (before insert and before update) to query the object and select the max value of your date field and compare it to the new record you're creating/editing. if it'snt greater than the existing record throw an error.

Example with Account and a custom field BillingDate__c (Date)

trigger AccountTrigger on Account (before insert, before update)
{
Date maxBillingDate;
for(AggregateResult agr : [SELECT MAX(BillingDate__c) billingDate FROM Account]);
{
  maxBillingDate = Date.valueOf(agr.get('billingDate');
}

for(Account acc : Trigger.new)
{
  if(acc.BillingDate__c < maxBillingDate)
   acc.AddError('the billing date must be greater than : '+ maxBillingDate);
}
}

Hope this would help you 
kuttibarani1.3897618179833977E12kuttibarani1.3897618179833977E12
Thanks buddy,  I modified your code:

trigger Trigger_LastSubmittedDateCheck on Daily_Call_Report__c (before insert, before update)
{
    Date LastDCRdate = date.valueOf( [SELECT MAX(DCR_Actual_Date__c) MaxDCRdate FROM Daily_Call_Report__c]);

    for(Daily_Call_Report__c DCR: Trigger.new)
    {
       if(DCR.DCR_Actual_Date__c < LastDCRdate)
       DCR.AddError('You should continue DCR from next day to : ' + LastDCRdate );
    }
}

But it shows the bellow error...
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger Trigger_LastSubmittedDateCheck caused an unexpected exception, contact your administrator: Trigger_LastSubmittedDateCheck: execution of BeforeInsert caused by: System.TypeException: Invalid date: common.apex.runtime.impl.SObjectList@4ef3897d: Trigger.Trigger_LastSubmittedDateCheck: line 3, column 1


Is it because of date format?  The dateformat from the form field is dd/mm/yyyy and the format from the query is yyyy-mm-dd