You are here

public function EntityBrowserForm::buildForm in Entity Browser 8.2

Same name and namespace in other branches
  1. 8 src/Form/EntityBrowserForm.php \Drupal\entity_browser\Form\EntityBrowserForm::buildForm()

Form constructor.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The form structure.

Overrides FormInterface::buildForm

File

src/Form/EntityBrowserForm.php, line 141

Class

EntityBrowserForm
The entity browser form.

Namespace

Drupal\entity_browser\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {

  // During the initial form build, add this form object to the form state and
  // allow for initial preparation before form building and processing.
  if (!$form_state
    ->has('entity_form_initialized')) {
    $this
      ->init($form_state);
  }
  $this
    ->isFunctionalForm();
  $form['#attributes']['class'][] = 'entity-browser-form';
  if (!empty($form_state
    ->get([
    'entity_browser',
    'instance_uuid',
  ]))) {
    $form['#attributes']['data-entity-browser-uuid'] = $form_state
      ->get([
      'entity_browser',
      'instance_uuid',
    ]);
  }
  $form['#browser_parts'] = [
    'widget_selector' => 'widget_selector',
    'widget' => 'widget',
    'selection_display' => 'selection_display',
  ];
  if (!($current_widget_id = $this
    ->getCurrentWidget($form_state))) {
    $this->messenger
      ->addWarning($this
      ->t('No widgets are available.'));
    return $form;
  }
  $this->entityBrowser
    ->getWidgetSelector()
    ->setDefaultWidget($current_widget_id);
  $form[$form['#browser_parts']['widget_selector']] = $this->entityBrowser
    ->getWidgetSelector()
    ->getForm($form, $form_state);
  $widget = $this->entityBrowser
    ->getWidget($current_widget_id);
  if ($widget
    ->access()
    ->isAllowed()) {
    $form[$form['#browser_parts']['widget']] = $widget
      ->getForm($form, $form_state, $this->entityBrowser
      ->getAdditionalWidgetParameters());
  }
  else {
    $this->messenger
      ->addWarning($this
      ->t('Access to the widget forbidden.'));
  }

  // Add cache access cache metadata from the widgets to the form directly as
  // it is affected.
  foreach ($this->entityBrowser
    ->getWidgets() as $widget) {

    /** @var \Drupal\entity_browser\WidgetInterface $widget */
    $this->renderer
      ->addCacheableDependency($form, $widget
      ->access());
  }
  $form[$form['#browser_parts']['selection_display']] = $this->entityBrowser
    ->getSelectionDisplay()
    ->getForm($form, $form_state);
  if ($this->entityBrowser
    ->getDisplay() instanceof DisplayAjaxInterface) {
    $this->entityBrowser
      ->getDisplay()
      ->addAjax($form);
  }
  $form['#attached']['library'][] = 'entity_browser/entity_browser';
  return $form;
}