You are here

function insert_media_insert_process in Insert 8.2

Implements hook_insert_process().

File

modules/insert_media/insert_media.module, line 119

Code

function insert_media_insert_process(&$insertType, array &$element) {
  if ($insertType !== INSERT_TYPE_MEDIA) {
    return [];
  }
  $settings = $element['#insert_media']['settings'];
  $element['#insert']['settings']['styles'] = $settings['view_modes'];
  $element['#insert']['settings']['default'] = $settings['default'];

  /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager */
  $entityTypeManager = \Drupal::entityTypeManager();
  foreach ($element['selection'] as $key => &$selectionElement) {
    if (!is_int($key)) {
      continue;
    }
    $media = Media::load($element['selection'][$key]['target_id']['#value']);
    $entityTypeId = $media
      ->getEntityTypeId();
    $viewBuilder = $entityTypeManager
      ->getViewBuilder($entityTypeId);
    $selectionElement['insert'] = $element['insert'];
    $selectionElement['insert']['templates'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'insert-templates',
        ],
      ],
    ];
    $options = [];
    foreach (array_values($settings['view_modes']) as $id) {
      if ($id === 0) {
        continue;
      }
      $viewMode = $entityTypeManager
        ->getStorage('entity_view_mode')
        ->load('media.' . $id);
      if ($viewMode) {
        $view = $viewBuilder
          ->view($media, $id);
        $markup = render($view);
        $selectionElement['insert']['templates'][$id] = [
          '#type' => 'hidden',
          '#name' => 'template[' . $id . ']',
          '#value' => $markup
            ->__toString(),
        ];
        $options[$id] = $viewMode
          ->label();
      }
    }
    if (count($options) === 1) {
      $selectionElement['insert']['view_modes'] = [
        '#type' => 'hidden',
        '#value' => array_keys($options)[0],
      ];
    }
    else {
      $selectionElement['insert']['view_modes'] = [
        '#type' => 'select',
        '#options' => $options,
        '#default_value' => $settings['default'],
      ];
    }
  }
  $element['#attached']['library'][] = 'insert_media/insert_media';
  return [
    'selection',
  ];
}