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.
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.
protected static function prepareDeltaPositionConvert(array &$widget_state, FormStateInterface $form_state, array $field_path, $new_delta) {
// 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);
}