Create a simple module for Drupal 8 - Step 2 - Create Simple Page | Drupal 8

Create a simple module for Drupal 8 - Step 2 - Create Simple Page

Submitted by editor on Sat, 11/14/2015 - 13:03
Question

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");
}

File

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.