From 48d0af7d907f50696eaf37036ee24e1d161b1b66 Mon Sep 17 00:00:00 2001
From: paper boy <lowfidelity@1620860.no-reply.drupal.org>
Date: Sun, 26 Apr 2020 00:08:25 +0200
Subject: [PATCH] Issue #3061620 by joachim: Close only the IEF form and it's
 nested IEF elements where 'cancel' is clicked.

---
 .../FieldWidget/InlineEntityFormComplex.php      | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/src/Plugin/Field/FieldWidget/InlineEntityFormComplex.php b/src/Plugin/Field/FieldWidget/InlineEntityFormComplex.php
index 24b38e8..b34419b 100644
--- a/src/Plugin/Field/FieldWidget/InlineEntityFormComplex.php
+++ b/src/Plugin/Field/FieldWidget/InlineEntityFormComplex.php
@@ -1000,8 +1000,20 @@ class InlineEntityFormComplex extends InlineEntityFormBase implements ContainerF
    *   The form state of the parent form.
    */
   public static function closeChildForms($form, FormStateInterface &$form_state) {
-    $element = inline_entity_form_get_element($form, $form_state);
-    inline_entity_form_close_all_forms($element, $form_state);
+    // Get the button triggering this action.
+    $triggering_element = $form_state->getTriggeringElement();
+    // Slice  off 'ief_edit_cancel' and 'actions' keys from it's array parents to get to the inline_entity_form.
+    $array_parents = array_slice($triggering_element['#array_parents'], 0, -2);
+    // Get the parent IEF form element of the triggering button.
+    $element = NestedArray::getValue($form, $array_parents);
+
+    // Find and close all nested IEF forms of the triggering element.
+    foreach (Element::children($element) as $key) {
+      $iefId = NestedArray::getValue($element[$key], ['widget', '#ief_id']);
+      if(!empty($iefId)) {
+        inline_entity_form_close_all_forms($element[$key], $form_state);
+      }
+    }
   }
 
 }
-- 
2.17.1

