You are here

public function ComplexEntityFormModes::addPage in Form mode manager 8.2

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.

Overrides AbstractEntityFormModesFactory::addPage

File

src/ComplexEntityFormModes.php, line 31

Class

ComplexEntityFormModes
Route controller factory specific for each entities using bundles.

Namespace

Drupal\form_mode_manager

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
    ->getParameter('form_mode_name');
  $entity_routes_infos = $this->entityRoutingMap
    ->createInstance($entity_type_id, [
    'entityTypeId' => $entity_type_id,
  ])
    ->getPluginDefinition();
  $entity_type_cache_tags = $this->entityTypeManager
    ->getDefinition($entity_bundle_name)
    ->getListCacheTags();
  $build = [
    '#theme' => 'entity_add_list',
    '#bundles' => [],
    '#add_bundle_message' => $this
      ->t('There is no @entity_type yet.', [
      '@entity_type' => $entity_type_id,
    ]),
    '#cache' => [
      'tags' => Cache::mergeTags($entity_type_cache_tags, $this->formModeManager
        ->getListCacheTags()),
    ],
  ];
  $entity_type_definitions = $this->entityTypeManager
    ->getStorage($entity_bundle_name)
    ->loadMultiple();
  $entity_add_form = $entity_routes_infos['operations']['add_form'] . ".{$form_mode_name}";
  foreach ($entity_type_definitions as $bundle) {
    $bundle_name = $bundle
      ->id();
    if ($access = $this
      ->accessIsAllowed($entity_type_id, $bundle_name, $form_mode_name)) {
      $description = method_exists($bundle, 'getDescription') ? $bundle
        ->getDescription() : '';
      $build['#bundles'][$bundle_name] = [
        'label' => $bundle
          ->label(),
        'description' => $description,
        'add_link' => Link::createFromRoute($bundle
          ->label(), $entity_add_form, [
          $entity_bundle_name => $bundle
            ->id(),
        ]),
      ];
      $this->renderer
        ->addCacheableDependency($build, $access);
    }
  }

  // Bypass the entity/add listing if only one content type is available.
  if (1 == count($build['#bundles'])) {
    $bundle = current($build['#bundles']);
    $options = [
      'absolute' => TRUE,
    ];
    return new RedirectResponse(Url::fromRoute($entity_add_form, $bundle['add_link']
      ->getUrl()
      ->getRouteParameters(), $options)
      ->toString(), 302);
  }
  return $build;
}