You are here

public static function ParagraphsSets::prepareDeltaPosition in Paragraphs Sets 8.2

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.

1 call to ParagraphsSets::prepareDeltaPosition()
paragraphs_sets_field_widget_multivalue_form_alter in ./paragraphs_sets.module
Implements hook_field_widget_multivalue_form_alter().

File

src/ParagraphsSets.php, line 282

Class

ParagraphsSets
Utitlity class for paragraphs_sets.

Namespace

Drupal\paragraphs_sets

Code

public 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);
}