+ Start a Discussion
Ronaldo CostaRonaldo Costa 

Populating Lookupfields with parent related list records


Please let me know your approach for the case below as I did not find a similar requirement over the forum.

1- User creates a Flight Booking record (parent object)
2- The user creates a Stop record (up to 14) (child object)
3- The user creates a Flight Crew record (up to 5) (child object)
4- Once the user is done creating Stop records and Flight Crew records, the user will then check the Initiate Itinerary Automation checkbox to trigger the following actions:

The system will create a Flight Itinerary record (child object) and will populate several lookup fields (for all related Stops and Flight Crew)

What should be the easiest solution? Because I think I would need to query the Flight Booking to find out all IDs for the Stops and Flight Crew in order to populate the related lookup fields for each one of them.


I would actually do this off of a button from a Visualforce page or somthing similar instead of a trigger.  However here is how I would do it for a trigger.
trigger createItinerary on FlightBooking__c (after update) {
    Set<Id> bookingIds = new Set<Id>();

    for (FlightBooking__c booking : Trigger.new) {
        FlightBooking__c oldBooking = Trigger.oldMap.get(booking.Id);

        if (booking.AutomationFlag__c == true && booking.AutomationFlag__c != oldBooking.AutomationFlag__c) {

    if (!bookingIds.isEmpty()) {
        List<FlightItinerary__c> itineraries = new List<FlightItinerary__c>();
        for (FlightBooking__c booking : [
            select Name__c,
                    select Name__c
                    from Stop__r
                ), (
                    select Name__c
                    from Crew__r
            from FlightBooking__c
            where Id in :bookingIds
        ]) {
            for (Crew__c crew : booking.Crew__r) {   
                for (Stop__c stop : booking.Stop__r) {
                    itineraries.add(new FlightItinerary__c(
                        Booking__c = booking.Id,
                        Stop__c = stop.Id,
                        Crew__c = crew.Id

        if (!itineraries.isEmpty()) {
            insert itineraries;

This will create several itinerary objects based on each crew and stop.

NOTE: This code has not been tested and may contain typographical or logical errors.