You are here

public static function EntityBrowserFormTrait::processEntityBrowserSelected in Helper 8

Render API callback: Processes the table element.

File

src/EntityBrowserFormTrait.php, line 150

Class

EntityBrowserFormTrait
Provides helpers for adding an entity browser element to a form.

Namespace

Drupal\helper

Code

public static function processEntityBrowserSelected(&$element, FormStateInterface $form_state, &$complete_form) {
  $parents = array_slice($element['#array_parents'], -3, 2);
  $entity_ids = $form_state
    ->getValue(array_merge($parents, [
    'browser',
    'entity_ids',
  ]), '');
  $entities = empty($entity_ids) ? [] : self::loadEntityBrowserEntitiesByIds($entity_ids);
  $entity_type_manager = \Drupal::entityTypeManager();
  foreach ($entities as $id => $entity) {
    $entity_type_id = $entity
      ->getEntityTypeId();
    if ($entity_type_manager
      ->hasHandler($entity_type_id, 'view_builder')) {
      $preview = $entity_type_manager
        ->getViewBuilder($entity_type_id)
        ->view($entity, $element['#view_mode']);
    }
    else {
      $preview = [
        '#markup' => $entity
          ->label(),
      ];
    }
    $edit_button_access = !empty($element['#form_mode']) && $entity
      ->access('update', \Drupal::currentUser());
    $element[$id] = [
      '#attributes' => [
        'data-entity-id' => $id,
      ],
      'item' => $preview,
      'operations' => [
        'edit_button' => [
          '#type' => 'submit',
          '#value' => t('Edit'),
          '#name' => 'entity_browser_edit_' . $entity
            ->id() . '_' . md5(json_encode($element['#parents'])),
          '#ajax' => [
            'url' => Url::fromRoute('entity_browser.edit_form', [
              'entity_type' => $entity
                ->getEntityTypeId(),
              'entity' => $entity
                ->id(),
              'form_mode' => $element['#form_mode'],
            ]),
          ],
          '#attributes' => [
            'class' => [
              'edit-button',
            ],
          ],
          '#access' => $edit_button_access,
        ],
        'remove' => [
          '#type' => 'button',
          '#value' => t('Remove'),
          '#op' => 'remove',
          '#name' => 'entity_browser_remove_' . $id,
          '#ajax' => [
            'callback' => [
              self::class,
              'updateEntityBrowserSelected',
            ],
            'wrapper' => $element['#wrapper_id'],
          ],
        ],
      ],
    ];
  }
  return $element;
}