Subform : Recall existing data into subform - not create new data

Subform : Recall existing data into subform - not create new data

My use case is that I have a multi-select field where I want users to be able to choose locations that already exist and bring them into a subform to edit. The subform is linked - not an inline one. The multi-select field and the subform are the "locations" form.

I need to be able to fetch and update existing records, not create new ones

I can get the first part of the code to return the record for the last option chosen in the multi-select. I just need it to populate (and thereby link) the existing location record.

  1. //Use a null check to stop it running if there is nothing to match
  2. if(location[ID = input.locations].ID != null)
  3. {
  4.     varLocations = input.locations;
  5.     //create and clear the list as it's run every time something is added to the multiselect
  6.     varCollection = Collection();
  7.     varCollection.clear();
  8.     //Add all the selected locations to the collection
  9.     varCollection.insertall(input.locations);
  10.     //Get the size of the collection (minus a one because it's a zero index)
  11.     varLocationCount = varCollection.size() - 1;
  12.     //Now we just need the ID of the last location chosen
  13.     varLastLocation = varCollection.get(varLocationCount);
  14.    //
  15.     //Fetch the location about the chosen location
  16.     varFetchLocation = location[ID == varLastLocation];
  17.     //
  18.     // Here's where I try to add the fetched location to the subform
  19.           for each row in input.SUB_LOCATIONS
  20.           {
  21.           row.ID = varFetchLocation.ID;
  22.           row.location_name = varFetchLocation.location_name;
  23.           }
  24. }

Here's a visual example of my desired end result