How to create a simple page programmatically with Drupal 8
1. Create a info.yml file
Here : test.info.yml
name: 'Test Module'
description: 'Test module for Drupal8.ovh'
type: module
core: 8.x
varsion: 0.1-dev
package: Test
2. Create a .routing.yml
Here : test.routing.yml
test.my_page:
path: '/mypage'
defaults:
_controller: '\Drupal\test\Controller\TestController::home'
_title: 'My First Drupal 8 Page'
requirements:
_permission: 'access content'
3. Then create the Controller and put into module_root_folder/src/Controller/
Here : test/src/Controller/
<?php
/**
* @file
* @author Your Name
* Contains \Drupal\test\Controller\TestController.
*/
namespace Drupal\test\Controller;
/**
* Provides route responses for the Test module.
*/
class TestController {
/**
* Returns a simple page.
*
* @return array
* A simple renderable array.
*/
public function home() {
$element = array(
'#markup' => 'Hello. This is my First Page',
);
return $element;
}
}
4. Now you can visit your programmatically created page from your.domain/mypage
More about custom access control : https://atendesigngroup.com/blog/restricting-access-drupal-8-controllers
Tips: Set page title
$request = \Drupal::request();
if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
$route->setDefault('_title', "Access denied");
}
Comments