logo

Palette - Make it Colorful🎨

Palette - Visual Page Builder, no design degree required.

Live Demo Download Palette

Scroll

Drupal Create page programmatically

22/02/2025, by Anonymous (not verified)
Permalink

Routing YAML file for the Example module

The routing information is stored in example/example.routing.yml:

example.my_page:
  path: '/mypage/page'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::myPage'
    _title: 'My first page in D8'
  requirements:
    _permission: 'access content'
example.my_page
This is the machine name of the route. By convention, route machine names should be module_name.sub_name. When other parts of the code need to refer to the route, they will use the machine name.
path
This gives the path to the page on your site. Note the leading slash (/).
 
defaults
This describes the page and title callbacks. @todo: Where can these defaults be overridden?
 
requirements
This specifies the conditions under which the page will be displayed. You can specify permissions, modules that must be enabled, and other conditions.
 
 

Page implementation for the Example module

The Controller class ExampleController should be defined in example/src/Controller/ExampleController.php:

<?php
namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Provides route responses for the Example module.
 */
class ExampleController extends ControllerBase {

  /**
   * Returns a simple page.
   *
   * @return array
   *   A simple renderable array.
   */
  public function myPage() {
    $element = array(
      '#markup' => 'Hello, world',
    );
    return $element;
  }

}
namespace
This declares the prefix needed to fully qualify the name of the class we are defining. Compare the file's doc block and the name of the class. The class auto-loader knows that, to find the class \Drupal\example\Controller\ExampleController, it should look for the file modules/example/src/Controller/ExampleController.php.
use
This allows us to use ControllerBase instead of the fully qualified name. This makes our class line much easier to read.
myPage()
The method specified in the YAML file must be public. It should return a renderable array.

Drupal API documentation:

https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-page