From d1f5b5c93f950be176b557cf9671a69b437150f3 Mon Sep 17 00:00:00 2001
From: itamair <itamair@me.com>
Date: Sat, 27 Jun 2020 21:19:59 +0200
Subject: [PATCH] further tmp implementation

---
 js/layout-paragraphs-widget.js                | 23 +++---
 .../FieldWidget/LayoutParagraphsWidget.php    | 70 ++++++++++++-------
 2 files changed, 57 insertions(+), 36 deletions(-)

diff --git a/js/layout-paragraphs-widget.js b/js/layout-paragraphs-widget.js
index 325507ef..02ea0466 100644
--- a/js/layout-paragraphs-widget.js
+++ b/js/layout-paragraphs-widget.js
@@ -578,7 +578,7 @@
           });
         });
       /**
-       * Click hanlders for "Add New Section" buttons.
+       * Click handlers for "Add New Section" buttons.
        */
       $(".layout-paragraphs-field", context)
         .once("layout-paragraphs-add-section")
@@ -617,15 +617,18 @@
       /**
        * Add drag/drop/move controls.
        */
-      $(".layout-paragraphs-item", context)
-        .once("layout-paragraphs-controls")
-        .each((layoutParagraphsItemIndex, layoutParagraphsItem) => {
-          $('<div class="layout-controls">')
-            .append($('<div class="layout-handle">'))
-            .append($('<div class="layout-up">').click(moveUp))
-            .append($('<div class="layout-down">').click(moveDown))
-            .prependTo(layoutParagraphsItem);
-        });
+
+      if (!settings.paragraphsLayoutWidget.isTranslating) {
+        $(".layout-paragraphs-item", context)
+          .once("layout-paragraphs-controls")
+          .each((layoutParagraphsItemIndex, layoutParagraphsItem) => {
+            $('<div class="layout-controls">')
+              .append($('<div class="layout-handle">'))
+              .append($('<div class="layout-up">').click(moveUp))
+              .append($('<div class="layout-down">').click(moveDown))
+              .prependTo(layoutParagraphsItem);
+          });
+      }
       /**
        * Enhance radio buttons.
        */
diff --git a/src/Plugin/Field/FieldWidget/LayoutParagraphsWidget.php b/src/Plugin/Field/FieldWidget/LayoutParagraphsWidget.php
index f0afea50..d55fcd5b 100644
--- a/src/Plugin/Field/FieldWidget/LayoutParagraphsWidget.php
+++ b/src/Plugin/Field/FieldWidget/LayoutParagraphsWidget.php
@@ -314,7 +314,7 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
         '#type' => 'value',
         '#value' => $entity,
       ],
-      'toggle_button' => $this->toggleButton('layout-paragraphs-parent-uuid'),
+      'toggle_button' => $this->allowReferenceChanges() ? $this->toggleButton('layout-paragraphs-parent-uuid') : [],
       // Edit and remove button.
       'actions' => [
         '#type' => 'container',
@@ -339,12 +339,6 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
           '#name' => 'remove_' . $this->wrapperId . '_' . $delta,
           '#value' => $this->t('Remove'),
           '#attributes' => ['class' => ['layout-paragraphs-remove']],
-          '#limit_validation_errors' => [
-            array_merge($parents, [
-              $this->fieldName,
-              $delta,
-            ]),
-          ],
           '#limit_validation_errors' => [],
           '#submit' => [[$this, 'removeItemSubmit']],
           '#delta' => $delta,
@@ -369,7 +363,7 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
               'layout-paragraphs-layout-region--' . $region_name,
             ],
           ],
-          'toggle_button' => $this->toggleButton('layout-paragraphs-uuid'),
+          'toggle_button' => $this->allowReferenceChanges() ? $this->toggleButton('layout-paragraphs-uuid') : [],
         ];
       }
     }
@@ -579,7 +573,11 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
         '#host' => $items->getEntity(),
         '#value' => $this->t('Create New'),
         '#submit' => [[$this, 'newItemSubmit']],
-        '#limit_validation_errors' => [array_merge($parents, [$this->fieldName, 'add_more'])],
+        '#limit_validation_errors' => [array_merge($parents, [
+          $this->fieldName,
+          'add_more',
+        ]),
+        ],
         '#attributes' => ['class' => ['layout-paragraphs-add-item']],
         '#ajax' => [
           'callback' => [$this, 'editItemAjax'],
@@ -650,6 +648,7 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
           'search_text' => $this->t('Search'),
         ],
       ];
+      $elements['toggle_button'] = $this->toggleButton();
     }
     else {
       // Add the #isTranslating attribute, if in a translation context.
@@ -660,7 +659,6 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
       ];
     }
 
-    $elements['toggle_button'] = $this->toggleButton();
     if ($widget_state['open_form'] !== FALSE) {
       $this->entityForm($elements, $form_state, $form);
     }
@@ -689,8 +687,13 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
       ],
     ];
 
-    $elements['#attached']['drupalSettings']['paragraphsLayoutWidget']['maxDepth'] = $this->getSetting('nesting_depth');
-    $elements['#attached']['drupalSettings']['paragraphsLayoutWidget']['requireLayouts'] = $this->getSetting('require_layouts');
+    // Pass specific paragraphsLayoutWidget settings to js.
+    $elements['#attached']['drupalSettings']['paragraphsLayoutWidget'] = [
+      'maxDepth' => $this->getSetting('nesting_depth'),
+      'requireLayouts' => $this->getSetting('require_layouts'),
+      'isTranslating' => $elements["add_more"]["actions"]["#isTranslating"] ?? NULL,
+    ];
+    // Add layout_paragraphs_widget library.
     $elements['#attached']['library'][] = 'layout_paragraphs/layout_paragraphs_widget';
     return $elements;
   }
@@ -870,6 +873,10 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
 
     /** @var \Drupal\paragraphs\Entity\Paragraph $entity */
     $entity = $widget_state['items'][$delta]['entity'];
+    // Set correct default language for the entity.
+    if ($this->isTranslating && $language = $form_state->get('langcode')) {
+      $entity = $entity->getTranslation($language);
+    }
     $display = EntityFormDisplay::collectRenderDisplay($entity, 'default');
     $bundle_label = $entity->type->entity->label();
     $element['entity_form'] = [
@@ -1117,6 +1124,7 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
         ],
       ],
     ];
+
     $hide_untranslatable_fields = $entity->isDefaultTranslationAffectedOnly();
     foreach (Element::children($element['entity_form']) as $field) {
       if ($entity->hasField($field)) {
@@ -1516,31 +1524,36 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
     // Remove is_new flag since we're saving the entity.
     unset($widget_state['items'][$delta]['is_new']);
 
-    /** @var \Drupal\paragraphs\ParagraphInterface $paragraph_entity */
-    $paragraph_entity = $widget_state['items'][$delta]['entity'];
+    /** @var \Drupal\paragraphs\ParagraphInterface $paragraph */
+    $paragraph = $widget_state['items'][$delta]['entity'];
 
-    // Set correct default language for the paragraph.
-    $paragraph_entity->set('langcode', $form_state->get('langcode'));
-    $widget_state['items'][$delta]['entity'] = $paragraph_entity;
+    // Set correct default language for the entity.
+    if ($this->isTranslating && $language = $form_state->get('langcode')) {
+      $paragraph = $paragraph->getTranslation($language);
+    }
 
     // Save field values to entity.
-    $display->extractFormValues($paragraph_entity, $item_form, $form_state);
+    $display->extractFormValues($paragraph, $item_form, $form_state);
 
     // Submit behavior forms.
-    $paragraphs_type = $paragraph_entity->getParagraphType();
+    $paragraphs_type = $paragraph->getParagraphType();
     if ($this->currentUser->hasPermission('edit behavior plugin settings')) {
       foreach ($paragraphs_type->getEnabledBehaviorPlugins() as $plugin_id => $plugin_values) {
-        if (!empty($item_form['behavior_plugins'][$plugin_id])) {
+        $plugin_form = isset($item_form['behavior_plugins']) ? $item_form['behavior_plugins'][$plugin_id] : [];
+        if (!empty($plugin_form) && !empty(Element::children($plugin_form))) {
           $subform_state = SubformState::createForSubform($item_form['behavior_plugins'][$plugin_id], $form_state->getCompleteForm(), $form_state);
-          $plugin_values->submitBehaviorForm($paragraph_entity, $item_form['behavior_plugins'][$plugin_id], $subform_state);
+          $plugin_values->submitBehaviorForm($paragraph, $item_form['behavior_plugins'][$plugin_id], $subform_state);
         }
       }
     }
 
+    // Save paragraph back to widget state.
+    $widget_state['items'][$delta]['entity'] = $paragraph;
+
     // Save layout settings.
     if (!empty($item_form['layout_selection']['layout'])) {
 
-      $layout_settings = $this->getLayoutSettings($paragraph_entity);
+      $layout_settings = $this->getLayoutSettings($paragraph);
       $layout = $form_state->getValue($item_form['layout_selection']['layout']['#parents']);
       $layout_settings['layout'] = $layout;
 
@@ -1555,7 +1568,7 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
             $layout_settings['config'] = $layout_instance->getConfiguration();
           }
 
-          $this->setLayoutSettings($paragraph_entity, $layout_settings);
+          $this->setLayoutSettings($paragraph, $layout_settings);
         }
         catch (\Exception $e) {
           watchdog_exception('Layout Paragraphs, Layout Instance generation', $e);
@@ -1566,7 +1579,7 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
       if (isset($item_form['layout_selection']['move_items'])) {
         $move_items = $form_state->getValue($item_form['layout_selection']['move_items']['#parents']);
         if ($move_items && isset($move_items['items'])) {
-          $parent_uuid = $paragraph_entity->uuid();
+          $parent_uuid = $paragraph->uuid();
           foreach ($move_items['items'] as $from_region => $to_region) {
             foreach ($widget_state['items'] as $delta => $item) {
               $layout_settings = $this->getLayoutSettings($item['entity']);
@@ -2172,12 +2185,17 @@ class LayoutParagraphsWidget extends WidgetBase implements ContainerFactoryPlugi
    * @param \Drupal\Core\Layout\LayoutInterface $layout
    *   The layout plugin.
    *
-   * @return \Drupal\Core\Plugin\PluginFormInterface
+   * @return \Drupal\Core\Plugin\PluginFormInterface|null
    *   The plugin form for the layout.
    */
   protected function getLayoutPluginForm(LayoutInterface $layout) {
     if ($layout instanceof PluginWithFormsInterface) {
-      return $this->pluginFormFactory->createInstance($layout, 'configure');
+      try {
+        return $this->pluginFormFactory->createInstance($layout, 'configure');
+      }
+      catch (\Exception $e) {
+        watchdog_exception('Erl, Layout Configuration', $e);
+      }
     }
 
     if ($layout instanceof PluginFormInterface) {
-- 
GitLab