public static function ParagraphsWidget::duplicateSubmit

Creates a duplicate of the paragraph entity.

File

paragraphs/src/Plugin/Field/FieldWidget/ParagraphsWidget.php, line 2131

Class

ParagraphsWidget
Plugin implementation of the 'entity_reference_revisions paragraphs' widget.

Namespace

Drupal\paragraphs\Plugin\Field\FieldWidget

Code

public static function duplicateSubmit(array $form, FormStateInterface $form_state) {
  $button = $form_state
    ->getTriggeringElement();

  // Go one level up in the form, to the widgets container.
  $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -5));
  $field_name = $element['#field_name'];
  $parents = $element['#field_parents'];
  $filed_path = array_slice($button['#parents'], 0, -5);

  // Inserting new element in the array.
  $widget_state = static::getWidgetState($parents, $field_name, $form_state);

  // Map the button delta to the actual delta.
  $original_button_delta = $button['#delta'];
  $position = array_search($button['#delta'], $widget_state['original_deltas']) + 1;
  static::prepareDeltaPosition($widget_state, $form_state, $filed_path, $position);

  /** @var \Drupal\Core\Entity\EntityInterface $entity */
  $entity = $widget_state['paragraphs'][$original_button_delta]['entity'];
  $widget_state = static::autocollapse($widget_state);

  // Check if the replicate module is enabled.
  if (\Drupal::hasService('replicate.replicator')) {
    $duplicate_entity = \Drupal::getContainer()
      ->get('replicate.replicator')
      ->cloneEntity($entity);
  }
  else {
    $duplicate_entity = $entity
      ->createDuplicate();
  }

  // Create the duplicated paragraph and insert it below the original.
  $widget_state['paragraphs'][] = [
    'entity' => $duplicate_entity,
    'display' => $widget_state['paragraphs'][$original_button_delta]['display'],
    'mode' => 'edit',
  ];
  static::setWidgetState($parents, $field_name, $form_state, $widget_state);
  $form_state
    ->setRebuild();
}