'Drupal 9: implementing custom functionality in PHP
I would really appreciate it if somebody would give me some hints about implementing/inserting custom functionality into a drupal 9 page with PHP code. I am trying to write a PHP function that is generating a file based on some specific properties of Drupal users on a button click, and I do not know where to start. I am really confused. Is there an easy way to insert PHP code into a Drupal basic page? I am searching for solutions, but what I always find is custom modules where none of the given examples is working
Solution 1:[1]
I would recommend to you to start from the basics. If you need some custom code based on Users' information, you will need to create a custom module.
Try to watch tutorials from Drupalize.me https://drupalize.me/series/module-development-guide
Solution 2:[2]
you could start creating a new folder inside web/modules/custom/ with your module name. Something like: web/modules/custom/my_custom_module
You should need these files to start:
- my_custom_module.info.yml
- my_custom_module.routing.yml
my_custom_module.info.yml
name: my_custom_module
type: module
description: 'Defines my_custom_module functionality'
core_version_requirement: ^8 || ^9
package: Custom
my_custom_module.routing.yml
my_custom_module.hello_world:
path: '/hello-world'
defaults:
_controller: '\Drupal\my_custom_module\Controller\MyCustomClass::helloWorld'
_title: 'Display an Hello World'
requirements:
_access: 'TRUE'
src/Controller/MyCustomClass.php
Inside your custom module folder, create this structure of folders src/Controller/ and the name of the class you want, in this example is MyCustomClass.php
We'll extend from ControllerBase and will be sufficient to allow us to create custom functionalities.
<?php
namespace Drupal\my_custom_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;
class MyCustomClass extends ControllerBase {
public function helloWorld() {
return new Response("Hello World");
}
}
It could be a good point to start learning and developing.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Carol Pettirossi |
| Solution 2 | Pablo Nicolas |
