In the most example of drupal8 you will experiment the Hello World module. This is just a demostration how you can create your custom module within the new drupal8 concept.
But your application can be more complicated as just a Hello World module, you want may be create one module, multiple route and a custom twig template for each route
User case is if you want to create your own module but managing a multiple Route within one module.
When you add a new yaml file you should uninstall the modul and insatll it again. I haven’t found other solution for this right now ! This will help you if you can’t see any changes when you add some configuration or yml files.Or when you get following error:
Theme hook YOUR-TEMPLATE not found.
Let say you want to create a module to manage contact and edit them. My Module in this case is named “mymodule”
Let start to create the diffrent route in “mymodule.routing.yml” file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
mymodule.contacts_show: path: '/contacts/show' defaults: _controller: '\Drupal\database\Controller\ContactController::getContacts' _title: 'Contacts' requirements: _permission: 'access content' mymodule.contact_edit: path: '/contact/edit/{id}' defaults: _controller: '\Drupal\database\Controller\ContactController::editContact' _title: 'Edit Contact' requirements: _permission: 'access content' |
Add your Conroller in src folder with the name ContactController.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php namespace Drupal\mymodule\Controller; use Drupal\Core\Controller\ControllerBase; class ContactController extends ControllerBase { public function getContacts($name) { //here you can define you business logic, like Database querys , forms ...and you can transmit variable in the return array return [ '#theme' => 'contacts_show_page']; } public function editContact($id) { return [ '#theme' => 'contact_edit_page', '#id' => $id ]; } } ?> |
Create following yml file “mymodule.module”:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php /** * Implements hook_theme(). */ function database_theme() { $templates = array('contacts_show_page' => array('template' =>'contacts_show'), 'contact_edit_page' => array('variables' => ['id' => NULL],'template' => 'contact_edit') ); return $templates; } |
At the end just create the Twig templates within your templates folder:
templates/contact_edit.html.twig
1 |
This is id : {{id}} |
templates/contacts_show.html.twig
1 |
This is the Contacts show twig template |
So now, you are able to create diffrent routes and templates using Drupal8 and transfer variables from the controller to the twig template
using your own business logic operations.