You are here

protected static function ParagraphsWidget::prepareDeltaPosition in Paragraphs 8

Prepares the widget state to add a new paragraph at a specific position.

In addition to the widget state change, also user input could be modified to handle adding of a new paragraph at a specific position between existing paragraphs.

Parameters

array $widget_state: Widget state as reference, so that it can be updated.

\Drupal\Core\Form\FormStateInterface $form_state: Form state.

array $field_path: Path to paragraph field.

int|mixed $new_delta: Delta position in list of paragraphs, where new paragraph will be added.

2 calls to ParagraphsWidget::prepareDeltaPosition()
ParagraphsWidget::addMoreSubmit in src/Plugin/Field/FieldWidget/ParagraphsWidget.php
Submission handler for the "Add another item" button.
ParagraphsWidget::duplicateSubmit in src/Plugin/Field/FieldWidget/ParagraphsWidget.php
Creates a duplicate of the paragraph entity.

File

src/Plugin/Field/FieldWidget/ParagraphsWidget.php, line 1756

Class

ParagraphsWidget
Plugin implementation of the 'entity_reference_revisions paragraphs' widget.

Namespace

Drupal\paragraphs\Plugin\Field\FieldWidget

Code

protected static function prepareDeltaPosition(array &$widget_state, FormStateInterface $form_state, array $field_path, $new_delta) {

  // Increase number of items to create place for new paragraph.
  $widget_state['items_count']++;

  // Default behavior is adding to end of list and in case delta is not
  // provided or already at end, we can skip all other steps.
  if (!is_numeric($new_delta) || intval($new_delta) >= $widget_state['real_item_count']) {
    return;
  }
  $widget_state['real_item_count']++;

  // Limit delta between 0 and "number of items" in paragraphs widget.
  $new_delta = max(intval($new_delta), 0);

  // Change user input in order to create new delta position.
  $user_input = NestedArray::getValue($form_state
    ->getUserInput(), $field_path);

  // Rearrange all original deltas to make one place for the new element.
  $new_original_deltas = [];
  foreach ($widget_state['original_deltas'] as $current_delta => $original_delta) {
    $new_current_delta = $current_delta >= $new_delta ? $current_delta + 1 : $current_delta;
    $new_original_deltas[$new_current_delta] = $original_delta;
    $user_input[$original_delta]['_weight'] = $new_current_delta;
  }

  // Add information into delta mapping for the new element.
  $original_deltas_size = count($widget_state['original_deltas']);
  $new_original_deltas[$new_delta] = $original_deltas_size;
  $user_input[$original_deltas_size]['_weight'] = $new_delta;
  $widget_state['original_deltas'] = $new_original_deltas;
  NestedArray::setValue($form_state
    ->getUserInput(), $field_path, $user_input);
}