You are here

class MenuExampleController in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/menu_example/src/Controller/MenuExampleController.php \Drupal\menu_example\Controller\MenuExampleController

Controller routines for menu example routes.

The response of Drupal's HTTP Kernel system's request is generated by a piece of code called the controller.

In Drupal 8, we use a controller class for placing those piece of codes in methods which responds to a route.

This file will be placed at {module_name}/src/Controller directory. Route entries uses a key '_controller' to define the method called from controller class.

Hierarchy

Expanded class hierarchy of MenuExampleController

See also

https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-r...

File

menu_example/src/Controller/MenuExampleController.php, line 25

Namespace

Drupal\menu_example\Controller
View source
class MenuExampleController extends ControllerBase {
  use DescriptionTemplateTrait;

  /**
   * {@inheritdoc}
   */
  protected function getModuleName() {
    return 'menu_example';
  }

  /**
   * Page callback for the simplest introduction menu entry.
   *
   * The controller callback defined menu_examples.routing.yml file,
   * maps the path 'examples/menu-example' to this method.
   *
   * @throws \InvalidArgumentException
   */
  public function basicInstructions() {
    return [
      $this
        ->description(),
    ];
  }

  /**
   * Show a menu link in a menu other than the default "Navigation" menu.
   */
  public function alternateMenu() {
    return [
      '#markup' => $this
        ->t('This will be in the Main menu instead of the default Tools menu'),
    ];
  }

  /**
   * A menu entry with simple permissions using 'access protected menu example'.
   *
   * @throws \InvalidArgumentException
   */
  public function permissioned() {
    $url = Url::fromRoute('examples.menu_example.permissioned_controlled');
    return [
      '#markup' => $this
        ->t('A menu item that requires the "access protected menu example" permission is at @link', [
        '@link' => Link::createFromRoute($url
          ->getInternalPath(), $url
          ->getRouteName())
          ->toString(),
      ]),
    ];
  }

  /**
   * Only accessible when the user will be granted with required permission.
   *
   * The permission is defined in file menu_examples.permissions.yml.
   */
  public function permissionedControlled() {
    return [
      '#markup' => $this
        ->t('This menu entry will not show and the page will not be accessible without the "access protected menu example" permission to current user.'),
    ];
  }

  /**
   * Demonstrates the use of custom access check in routes.
   *
   * @throws \InvalidArgumentException
   *
   * @see \Drupal\menu_example\Controller\MenuExampleController::customAccessPage()
   */
  public function customAccess() {
    $url = Url::fromRoute('examples.menu_example.custom_access_page');
    return [
      '#markup' => $this
        ->t('A menu item that requires the user to posess a role of "authenticated" is at @link', [
        '@link' => Link::createFromRoute($url
          ->getInternalPath(), $url
          ->getRouteName())
          ->toString(),
      ]),
    ];
  }

  /**
   * Content will be displayed only if access check is satisfied.
   *
   * @see \Drupal\menu_example\Controller\MenuExampleController::customAccess()
   */
  public function customAccessPage() {
    return [
      '#markup' => $this
        ->t('This menu entry will not be visible and access will result
        in a 403 error unless the user has the "authenticated" role. This is
        accomplished with a custom access check plugin.'),
    ];
  }

  /**
   * Give the user a link to the route-only page.
   *
   * @throws \InvalidArgumentException
   */
  public function routeOnly() {
    $url = Url::fromRoute('examples.menu_example.route_only.callback');
    return [
      '#markup' => $this
        ->t('A menu entry with no menu link is at @link', [
        '@link' => Link::createFromRoute($url
          ->getInternalPath(), $url
          ->getRouteName())
          ->toString(),
      ]),
    ];
  }

  /**
   * Such callbacks can be user for creating web services in Drupal 8.
   */
  public function routeOnlyCallback() {
    return [
      '#markup' => $this
        ->t('The route entry has no corresponding menu links entry, so it provides a route without a menu link, but it is the same in every other way to the simplest example.'),
    ];
  }

  /**
   * Uses the path and title to determine the page content.
   *
   * This controller is mapped dynamically based on the 'route_callbacks:' key
   * in the routing YAML file.
   *
   * @param string $path
   *   Path/URL of menu item.
   * @param string $title
   *   Title of menu item.
   *
   * @return array
   *   Controller response.
   *
   * @see Drupal\menu_example\Routing\MenuExampleDynamicRoutes
   */
  public function tabsPage($path, $title) {
    $secondary = substr_count($path, '/') > 2 ? 'secondary ' : '';
    return [
      '#markup' => $this
        ->t('This is the @secondary tab "@tabname" in the "basic tabs" example.', [
        '@secondary' => $secondary,
        '@tabname' => $title,
      ]),
    ];
  }

  /**
   * Demonstrates use of optional URL arguments in for menu item.
   *
   * @param string $arg1
   *   First argument of URL.
   * @param string $arg2
   *   Second argument of URL.
   *
   * @return array
   *   Controller response.
   *
   * @see https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes
   */
  public function urlArgument($arg1, $arg2) {

    // Perpare URL for single arguments.
    $url_single = Url::fromRoute('examples.menu_example.use_url_arguments', [
      'arg1' => 'one',
    ]);

    // Prepare URL for multiple arguments.
    $url_double = Url::fromRoute('examples.menu_example.use_url_arguments', [
      'arg1' => 'one',
      'arg2' => 'two',
    ]);

    // Add these argument links to the page content.
    $markup = $this
      ->t('This page demonstrates using arguments in the url. For example, access it with @link_single for single argument or @link_double for two arguments in URL', [
      '@link_single' => Link::createFromRoute($url_single
        ->getInternalPath(), $url_single
        ->getRouteName(), $url_single
        ->getRouteParameters())
        ->toString(),
      '@link_double' => Link::createFromRoute($url_double
        ->getInternalPath(), $url_double
        ->getRouteName(), $url_double
        ->getRouteParameters())
        ->toString(),
    ]);

    // Process the arguments if they're provided.
    if (!empty($arg1)) {
      $markup .= '<div>' . $this
        ->t('Argument 1 = @arg', [
        '@arg' => $arg1,
      ]) . '</div>';
    }
    if (!empty($arg2)) {
      $markup .= '<div>' . $this
        ->t('Argument 2 = @arg', [
        '@arg' => $arg2,
      ]) . '</div>';
    }

    // Finally return the markup.
    return [
      '#markup' => $markup,
    ];
  }

  /**
   * Demonstrate generation of dynamic creation of page title.
   *
   * @see \Drupal\menu_example\Controller\MenuExampleController::backTitle()
   */
  public function titleCallbackContent() {
    return [
      '#markup' => $this
        ->t('The title of this page is dynamically changed by the title callback for this route defined in menu_example.routing.yml.'),
    ];
  }

  /**
   * Generates title dynamically.
   *
   * @see \Drupal\menu_example\Controller\MenuExampleController::titleCallback()
   */
  public function titleCallback() {
    return [
      '#markup' => $this
        ->t('The new title is your username: @name', [
        '@name' => $this
          ->currentUser()
          ->getDisplayName(),
      ]),
    ];
  }

  /**
   * Demonstrates how you can provide a placeholder url arguments.
   *
   * @throws \InvalidArgumentException
   *
   * @see \Drupal\menu_example\Controller\MenuExampleController::placeholderArgsDisplay()
   * @see https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes
   */
  public function placeholderArgs() {
    $url = Url::fromRoute('examples.menu_example.placeholder_argument.display', [
      'arg' => 3343,
    ]);
    return [
      '#markup' => $this
        ->t('Demonstrate placeholders by visiting @link', [
        '@link' => Link::createFromRoute($url
          ->getInternalPath(), $url
          ->getRouteName(), $url
          ->getRouteParameters())
          ->toString(),
      ]),
    ];
  }

  /**
   * Displays placeholder argument supplied in URL.
   *
   * @param int $arg
   *   URL argument.
   *
   * @return array
   *   URL argument.
   *
   * @see \Drupal\menu_example\Controller\MenuExampleController::placeholderArgs()
   */
  public function placeholderArgsDisplay($arg) {
    return [
      '#markup' => $arg,
    ];
  }

  /**
   * Demonstrate how one can alter the existing routes.
   */
  public function pathOverride() {
    return [
      '#markup' => $this
        ->t('This menu item was created strictly to allow the RouteSubscriber class to have something to operate on. menu_example.routing.yml defined the path as examples/menu-example/menu-original-path. The alterRoutes() changes it to /examples/menu-example/menu-altered-path. You can try navigating to both paths and see what happens!'),
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 40
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
DescriptionTemplateTrait::description public function Generate a render array with our templated content.
DescriptionTemplateTrait::getDescriptionTemplatePath protected function Get full path to the template.
DescriptionTemplateTrait::getDescriptionVariables protected function Variables to act as context to the twig template file. 1
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MenuExampleController::alternateMenu public function Show a menu link in a menu other than the default "Navigation" menu.
MenuExampleController::basicInstructions public function Page callback for the simplest introduction menu entry.
MenuExampleController::customAccess public function Demonstrates the use of custom access check in routes.
MenuExampleController::customAccessPage public function Content will be displayed only if access check is satisfied.
MenuExampleController::getModuleName protected function Name of our module. Overrides DescriptionTemplateTrait::getModuleName
MenuExampleController::pathOverride public function Demonstrate how one can alter the existing routes.
MenuExampleController::permissioned public function A menu entry with simple permissions using 'access protected menu example'.
MenuExampleController::permissionedControlled public function Only accessible when the user will be granted with required permission.
MenuExampleController::placeholderArgs public function Demonstrates how you can provide a placeholder url arguments.
MenuExampleController::placeholderArgsDisplay public function Displays placeholder argument supplied in URL.
MenuExampleController::routeOnly public function Give the user a link to the route-only page.
MenuExampleController::routeOnlyCallback public function Such callbacks can be user for creating web services in Drupal 8.
MenuExampleController::tabsPage public function Uses the path and title to determine the page content.
MenuExampleController::titleCallback public function Generates title dynamically.
MenuExampleController::titleCallbackContent public function Demonstrate generation of dynamic creation of page title.
MenuExampleController::urlArgument public function Demonstrates use of optional URL arguments in for menu item.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.