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
mxalix258mxalix258 

Sort child records by date

trigger accountTestTrggr on Account (before insert, before update) {

  List<Account> accountsWithContacts = [select id, name, (select id, salutation, description, 
                                                                firstname, lastname, email from Contacts) 
                                                                from Account where Id IN :Trigger.newMap.keySet()];
	  
  List<Contact> contactsToUpdate = new List<Contact>{};

  for(Account a: accountsWithContacts){

     for(Contact c: a.Contacts){
   	  c.Description=c.salutation + ' ' + c.firstName + ' ' + c.lastname; 

   	  contactsToUpdate.add(c);
     }    	  
   }
      
   update contactsToUpdate;
}

 

Taking this fairly simple code, how can I take the contacts from the second for loop, and either find the contact that was created most recently, or create a list and sort by created date? The trick is that it will have to be specific to the parent, so most recent contact, for each account record.

 

I'm not sure how to go about this, any thoughts?

 

Thank you!

Best Answer chosen by Admin (Salesforce Developers) 
Yoganand GadekarYoganand Gadekar

try to use child relationship query to access all the child records of parent record and then operate on the child records.

See if this explaination on Child relationship query  helps you: http://cloudforce4u.blogspot.in/2013/06/sometimes-we-need-list-of-all-child.html

 

For sorting the retrived child records you can use order by craeted date asc clause in the inner query.

 

MArk this as answer and hit kudos if it helps you.

All Answers

Yoganand GadekarYoganand Gadekar

try to use child relationship query to access all the child records of parent record and then operate on the child records.

See if this explaination on Child relationship query  helps you: http://cloudforce4u.blogspot.in/2013/06/sometimes-we-need-list-of-all-child.html

 

For sorting the retrived child records you can use order by craeted date asc clause in the inner query.

 

MArk this as answer and hit kudos if it helps you.

This was selected as the best answer
Sfd developerSfd developer

Hi,

 

If you change the query like below 

,

List<Account> accountsWithContacts = [select id, name, (select id, salutation, description,
                                                                  firstname, lastname, email from Contacts ORDER BY CreatedDate DESC LIMIT 1)
                                                                       from Account where Id IN :Trigger.newMap.keySet()];

 

 

This query gives the most recently created contact.

 

Thanks,