You are here

public static function MediaForm::updateWidget in GridStack 8.2

AJAX callback to update the widget when the selection changes.

File

src/Plugin/gridstack/stylizer/MediaForm.php, line 509

Class

MediaForm
Provides the media form for Layout Builder integration.

Namespace

Drupal\gridstack\Plugin\gridstack\stylizer

Code

public static function updateWidget(array $form, FormStateInterface $form_state) {
  $triggering_element = $form_state
    ->getTriggeringElement();
  $wrapper_id = $triggering_element['#ajax']['wrapper'];

  // This callback is either invoked from the remove button or the update
  // button, which have different nesting levels.
  $is_remove_button = end($triggering_element['#parents']) === 'remove_button';
  $length = $is_remove_button ? -3 : -1;
  if (count($triggering_element['#array_parents']) < abs($length)) {
    throw new \LogicException('The element that triggered the widget update was at an unexpected depth. Triggering element parents were: ' . implode(',', $triggering_element['#array_parents']));
  }
  $parents = array_slice($triggering_element['#array_parents'], 0, $length);
  $element = NestedArray::getValue($form, $parents);

  // Always clear the textfield selection to prevent duplicate additions.
  $element['media_library_selection']['#value'] = '';

  // @todo $field_state = static::getFieldState($element, $form_state);
  // Announce the updated content to screen readers.
  if ($is_remove_button) {
    $announcement = t('Media has been removed.');

    // At least it works here.
    unset($element['selection'][$element['#delta']]);
    $element['open_button']['#value'] = t('Add media');
  }
  else {
    $new_items = count(static::getNewMediaItems($element, $form_state));
    $announcement = \Drupal::translation()
      ->formatPlural($new_items, 'Added one media item.', 'Added @count media items.');
  }
  $response = new AjaxResponse();
  $response
    ->addCommand(new ReplaceCommand("#{$wrapper_id}", $element));
  $response
    ->addCommand(new AnnounceCommand($announcement));
  return $response;
}