Salesforce: Retrieve related list with SOQL and Apex

You are working with a Salesforce custom object, and you need to iterate through the related list. How do you retrieve the listed list with SOQL, and iterate through them with Apex? For the illustration purpose, I'm going to use Financial Force object, SCMC__Sales_Order__c. The SCMC__Sales_Order__c has a child relationship, SCMC__Purchase_Orders__r, as shown in the ( IDE) screenshot below.

We have a custom field ("customerNote") in Sales Order object, and we would like to copy this field into the same custom field ("customerNote") existing in the Purchase Order objects.

First we'll create a Apex Trigger on Sales Order object:

trigger SalesOrder on SCMC__Sales_Order__c (
        before insert, before update, after update) {

	if (Trigger.isBefore) {
	} else if (Trigger.isAfter) {

Now, that we created a Trigger we need to build business logic in an Apex Class -- SalesOrderTriggerHandler.

public with sharing class SalesOrderTriggerHandler {

    public static void beforeInsertUpdate(List salesOrders) {
	// some business logic for Before Insert, and Before Update trigger
    public static void afterUpdate(List salesOrders) {
        for (SCMC__Sales_Order__c so : salesOrders) {
	    // Retrieve the Customer Note field..
	    String customerNote = (String) so.get('customerNote__c');
	    // Only process if note field is not empty.
	    if ((customerNote != null) && (customerNote.length() >0)) {
                // The SO object about to be written does NOT have the
                // reference to SCMC__Purchase_Orders__r, so we'll have
                // to Query again.
		for (SCMC__Sales_Order__c mySo : [Select id, 
                   (Select id, FTP_credentials__c from SCMC__Purchase_Orders__r)
                    from SCMC__Sales_Order__c where Id = :so.Id]) {
			for (SCMC__Purchase_Order__c po : 
                                              mySo.SCMC__Purchase_Orders__r) {
			    po.customerNote__c = customerNote ;
			    update po;


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.