function NodeController::addPage

Same name in other branches
  1. 9 core/modules/node/src/Controller/NodeController.php \Drupal\node\Controller\NodeController::addPage()
  2. 8.9.x core/modules/node/src/Controller/NodeController.php \Drupal\node\Controller\NodeController::addPage()
  3. 11.x core/modules/node/src/Controller/NodeController.php \Drupal\node\Controller\NodeController::addPage()

Displays add content links for available content types.

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

Return value

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

1 string reference to 'NodeController::addPage'
node.routing.yml in core/modules/node/node.routing.yml
core/modules/node/node.routing.yml

File

core/modules/node/src/Controller/NodeController.php, line 70

Class

NodeController
Returns responses for Node routes.

Namespace

Drupal\node\Controller

Code

public function addPage() {
    $definition = $this->entityTypeManager()
        ->getDefinition('node_type');
    $build = [
        '#theme' => 'node_add_list',
        '#cache' => [
            'tags' => $this->entityTypeManager()
                ->getDefinition('node_type')
                ->getListCacheTags(),
        ],
    ];
    $content = [];
    $types = $this->entityTypeManager()
        ->getStorage('node_type')
        ->loadMultiple();
    uasort($types, [
        $definition->getClass(),
        'sort',
    ]);
    // Only use node types the user has access to.
    foreach ($types as $type) {
        $access = $this->entityTypeManager()
            ->getAccessControlHandler('node')
            ->createAccess($type->id(), NULL, [], TRUE);
        if ($access->isAllowed()) {
            $content[$type->id()] = $type;
        }
        $this->renderer
            ->addCacheableDependency($build, $access);
    }
    // Bypass the node/add listing if only one content type is available.
    if (count($content) == 1) {
        $type = array_shift($content);
        return $this->redirect('node.add', [
            'node_type' => $type->id(),
        ]);
    }
    $build['#content'] = $content;
    return $build;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.