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
Silpi roy 16Silpi roy 16 

Trigger to sort the records based on created date

There is custom obj and have a checkbox .
I want to sort the records based on Created date.
The checkbox should be checked for the record if created date is the oldest among the list of records.

 
HARSHIL U PARIKHHARSHIL U PARIKH
You are sorting data based on the created date, means the trigger would only fire once in its lifetime (unless you are deleting the records).

Couldn't you just manually check the checkbox on the object's record once you find out which one is the oldest record? You can find the oldest record from reports.

Again, if this is a case of deleting records then yes, autmation is needed. And below is a design I can offer to you Roy.

Steps:
1. Create a checkbox field named "Oldest Record" on an Object. (You may already have this)
2. Manually check the checkbox on the record which is oldest based on a created date.
3. You will need a trigger which fires on delete operation only. After Delete, After UnDelete. See my comments on trigger to build out a code.
 
Trigger FindOldestRecord on Contact (After Delete, After Undelete) {
	
    If(Trigger.IsAfter && Trigger.IsDelete)
    {
        /*
         * check if the deleted record had Oldest_Contact__c checkbox checked. If not, no code required. 
         * If yes,
         * You need to query all the existing records and find the oldest one.
         * Tip: make a use of "ORDER BY CreatedDate ASC" in your query. This will make your first record as an    oldest :)
         * set the checkbox to true and update the record.
         */
    }
    
    If(Trigger.IsAfter && Trigger.IsUnDelete)
    {
        /*
         * First find out if there is an existing record who has Oldest_Contact__c checked. if yes, match it's date with 
         * this newly undeleted record. Once matched, whichever wins, that's your new oldest conatct.
         * 
         */
    }
    
}

Hope this helps!