In the dynamic world of Drupal module development, creating custom forms for module settings is essential to offer administrators flexibility and control over module behavior. In this lesson, we'll explore how to leverage Drupal's Form API to create a robust settings form that integrates seamlessly with any custom module.
Understanding Drupal's Form API
Before diving into creating a form, it's crucial to understand Drupal's Form API, which provides a streamlined process for defining forms, handling submissions, and applying form-level validation. Using this API ensures consistency and provides built-in features like form caching and access control.
Setting Up Your Module
If you've followed previous lessons, you should have a custom module ready. Ensure your module is active and navigate to your custom module directory. We will proceed to create a settings form within our existing module structure.
Creating the Settings Form
The form will be created by implementing a Drupal Form class. Start by creating a Form
directory inside your module's src
directory:
mkdir -p src/Form
Next, create a new PHP file, SettingsForm.php
in the src/Form
directory. This file will contain your form definition:
// File: src/Form/SettingsForm.php
<?php
namespace Drupal\my_rest_module\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Configure settings for My REST Module.
*/
class SettingsForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['my_rest_module.settings'];
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'my_rest_module_settings_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('my_rest_module.settings');
$form['api_key'] = [
'#type' => 'textfield',
'#title' => $this->t('API Key'),
'#description' => $this->t('Provide the API key used for external services.'),
'#default_value' => $config->get('api_key'),
];
$form['api_endpoint'] = [
'#type' => 'url',
'#title' => $this->t('API Endpoint'),
'#description' => $this->t('Enter the API endpoint URL.'),
'#default_value' => $config->get('api_endpoint'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (!filter_var($form_state->getValue('api_endpoint'), FILTER_VALIDATE_URL)) {
$form_state->setErrorByName('api_endpoint', $this->t('The endpoint must be a valid URL.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->configFactory->getEditable('my_rest_module.settings')
->set('api_key', $form_state->getValue('api_key'))
->set('api_endpoint', $form_state->getValue('api_endpoint'))
->save();
parent::submitForm($form, $form_state);
}
}
This setup includes a form with fields for an API key and endpoint URL. The buildForm
method defines form elements, while validateForm
ensures URLs are valid before submission. Finally, submitForm
saves the settings using Drupal’s configuration system.
Adding the Form to the Administration Interface
To access the form in the Drupal admin interface, register it as a menu link. Within your module, add the following to my_rest_module.links.menu.yml
:
my_rest_module.settings:
title: 'My REST Module Settings'
description: 'Configure settings for My REST Module'
route_name: my_rest_module_settings_form
parent: system.admin_config_services
weight: 100
This configuration registers your settings page under the "Configuration" section in the admin interface.
Testing and Troubleshooting
Clear cache with drush cache-rebuild
and navigate to the configuration page in your admin interface. Test the form to ensure data is saved and validates correctly, adjusting your SettingsForm.php
code if needed.
Conclusion
By creating a settings form, you enable more dynamic module behavior by allowing administrators to configure the module's critical parameters. The skills gathered here will serve you in many future projects as form creation is a recurring need in Drupal development.
What’s Next?
Storing form data reliably is crucial. Next, we'll explore using the Config API in depth with our lesson on Storing Form Data in Config API, enhancing where and how Drupal stores configuration data efficiently.