You are here

public function EntityFormModeBase::addPage in Form mode manager 8

Displays add content links for available entity types.

Redirects to entity/add/[bundle] if only one content type is available.

Return value

array|\Symfony\Component\HttpFoundation\RedirectResponse A render array for a list of the entity types that can be added; however, if there is only one entity type defined for the site, the function will return a RedirectResponse to the entity add page for that one entity type.

File

src/Controller/EntityFormModeBase.php, line 144

Class

EntityFormModeBase
Controller for entity form mode support.

Namespace

Drupal\form_mode_manager\Controller

Code

public function addPage(RouteMatchInterface $route_match) {
  $entity_type_id = $route_match
    ->getRouteObject()
    ->getOption('_form_mode_manager_entity_type_id');
  $entity_bundle_name = $route_match
    ->getRouteObject()
    ->getOption('_form_mode_manager_bundle_entity_type_id');
  $form_mode_name = $route_match
    ->getRouteObject()
    ->getDefault('form_mode_name');
  $entity_type_cache_tags = $this->entityTypeManager
    ->getDefinition($entity_bundle_name)
    ->getListCacheTags();
  $entity_type_definitions = $this->entityTypeManager
    ->getStorage($entity_bundle_name)
    ->loadMultiple();
  $build = [
    '#theme' => 'form_mode_manager_add_list',
    '#entity_type' => $entity_type_id,
    '#cache' => [
      'tags' => Cache::mergeTags($entity_type_cache_tags, $this->formModeManager
        ->getListCacheTags()),
    ],
  ];
  $content = [];
  foreach ($entity_type_definitions as $bundle) {
    $bundle_id = $bundle
      ->id();
    $access = $this->entityTypeManager
      ->getAccessControlHandler($entity_type_id)
      ->createAccess($bundle_id, $this->account, [], TRUE);
    if ($access
      ->isAllowed() && $this->formModeManager
      ->isActive($entity_type_id, $bundle_id, $form_mode_name)) {
      $content[$bundle_id] = $bundle;
      $this->renderer
        ->addCacheableDependency($build, $access);
    }
  }

  // Bypass the entity/add listing if only one content type is available.
  if (1 == count($content)) {
    $bundle = array_shift($content);
    $entity_routes_infos = $this->entityRoutingMap
      ->createInstance($entity_type_id, [
      'entityTypeId' => $entity_type_id,
    ])
      ->getPluginDefinition();
    return $this
      ->redirect($entity_routes_infos['operations']['add_form'] . ".{$form_mode_name}", [
      $entity_bundle_name => $bundle
        ->id(),
    ]);
  }
  $build['#content'] = $content;
  $build['#form_mode'] = $form_mode_name;
  return $build;
}