Drupal 10 custom module example

name: Custom Module  

type: module  

description: 'A Drupal 10 custom module'  

core_version_requirement: ^10  

package: Custom  

dependencies:  

  - drupal:field
drupal_root/  
  modules/  
    custom/  
      custom_module/  
        custom_module.info.yml  
        custom_module.module  
        custom_module.routing.yml  
        src/  
          Controller/  
            CustomModuleController.php  
          Form/  
            CustomModuleForm.php
custom_module.content:  
  path: '/custom-page'  
  defaults:  
    _controller: '\Drupal\custom_module\Controller\CustomModuleController::content'  
    _title: 'Custom Page'  
  requirements:  
    _permission: 'access content'  
namespace Drupal\custom_module\Controller;  
  
use Drupal\Core\Controller\ControllerBase;  
  
class CustomModuleController extends ControllerBase {  
  
  /**  
   * Returns a simple page.  
   *  
   * @return array  
   *   A render array.  
   */  
  public function content() {  
    return [  
      '#markup' => $this->t('Welcome to the custom page!'),  
    ];  
  }  
  
}  
custom_module.form:  
  path: '/custom-form'  
  defaults:  
    _form: '\Drupal\custom_module\Form\CustomModuleForm'  
    _title: 'Custom Form'  
  requirements:  
    _permission: 'access content'
namespace Drupal\custom_module\Form;  
  
use Drupal\Core\Form\FormBase;  
use Drupal\Core\Form\FormStateInterface;  
  
class CustomModuleForm extends FormBase {  
  
  /**  
   * {@inheritdoc}  
   */  
  public function getFormId() {  
    return 'custom_module_form';  
  }  
  
  /**  
   * {@inheritdoc}  
   */  
  public function buildForm(array $form, FormStateInterface $form_state) {  
    $form['name'] = [  
      '#type' => 'textfield',  
      '#title' => $this->t('Name'),  
      '#required' => TRUE,  
    ];  
    $form['submit'] = [  
      '#type' => 'submit',  
      '#value' => $this->t('Submit'),  
    ];  
    return $form;  
  }  
  
  /**  
   * {@inheritdoc}  
   */  
  public function submitForm(array &$form, FormStateInterface $form_state) {  
    \Drupal::messenger()->addMessage($this->t('Hello, @name!', ['@name' => $form_state->getValue('name')]));  
  }  
  
}  

Leave a Reply

Your email address will not be published. Required fields are marked *

×