You are here

function paragraphs_ee_sets_field_widget_multivalue_form_alter in Paragraphs Editor Enhancements 8

Implements hook_field_widget_multivalue_form_alter().

File

modules/paragraphs_ee_sets/paragraphs_ee_sets.module, line 47
Main functions for "Paragraphs Sets Editor Enhancements" module.

Code

function paragraphs_ee_sets_field_widget_multivalue_form_alter(array &$elements, FormStateInterface $form_state, array $context) {

  /** @var \Drupal\paragraphs\Plugin\Field\FieldWidget\ParagraphsWidget $widget */
  $widget = $context['widget'];
  if (!$widget instanceof ParagraphsWidget) {
    return;
  }

  // Load third-party settings.
  $widget_third_party_settings = $widget
    ->getThirdPartySetting('paragraphs_sets', 'paragraphs_sets', []);
  if (empty($widget_third_party_settings['use_paragraphs_sets'])) {
    return;
  }
  $items = $context['items'];
  $field_definition = $items
    ->getFieldDefinition();

  // Get a list of all Paragraphs types allowed in this field.
  $field_allowed_paragraphs_types = $widget
    ->getAllowedTypes($field_definition);
  $sets = ParagraphsSets::getSets(array_keys($field_allowed_paragraphs_types));

  // Limit available sets from widget settings.
  if (isset($widget_third_party_settings['sets_allowed']) && count(array_filter($widget_third_party_settings['sets_allowed']))) {
    $sets = array_intersect_key($sets, array_filter($widget_third_party_settings['sets_allowed']));
  }
  foreach (array_keys($sets) as $key) {

    /** @var \Drupal\paragraphs_sets\ParagraphsSetInterface $set */
    if (empty($elements['add_more']["append_selection_button_{$key}"]) || ($set = ParagraphsSet::load($key)) === NULL) {
      continue;
    }
    $button =& $elements['add_more']["append_selection_button_{$key}"];

    // Use custom button layout.
    $button['#theme_wrappers'] = [
      'input__submit__paragraphs_action__image',
    ];
    $button['#attributes']['class'][] = 'paragraphs-button--add-more';
    $button['#description'] = $set
      ->getDescription();
    $button['#icon_attributes'] = new Attribute();
    $button['#icon_attributes']['aria-hidden'] = 'true';
    $button['#icon_attributes']['class'] = [
      'paragraphs-button--icon',
    ];
    if ($icon_url = $set
      ->getIconUrl()) {

      // Extract icon from button.
      $elements['add_more']["append_selection_button_{$key}"]['#attributes']['class'][] = 'icon';
      unset($button['#attributes']['style']);
      $button['#icon'] = $icon_url;
    }
    else {
      $button['#icon_attributes']['class'][] = 'image-default';
    }
  }
}