Creating an Admin Form in Drupal
In this guide, we'll walk through the steps to create an admin form in Drupal using the Drupal Console. This allows site editors to configure messages displayed to users when they log in.
Link to steps-to-create-an-admin-form headingSteps to Create an Admin Form
Generate the Form: Use the generate:form:config command in the Drupal Console.
drupal generate:form:configFollow the prompts:
- Module name:
welcome - Form Class name:
AdminSettingsForm - Form id: Leave as
admin_settings_form - Load services from the container: No
- Generate a form structure: Yes
- Type:
textarea - Input label:
Welcome message - Input machine name: Leave as
welcome_message - Description:
Welcome message display to users when they login - Default value:
Welcome to the site - Weight for input item: Leave as
0 - Another field: No
- Update routing file: Yes
- Generate a menu link: Yes
- Title for the menu link:
Welcome message configuration - Menu parent: Leave as
system.admin_config_system - Description of the menu link:
Welcome message admin
Generated Files: The Drupal Console will create and update several files:
modules/custom/welcome/src/Form/AdminSettingsForm.phpmodules/custom/welcome/config/install/welcome.adminsettings.ymlmodules/custom/welcome/welcome.links.menu.ymlmodules/custom/welcome/welcome.routing.yml
Check the Form: Add a welcome message in the textarea and submit. To verify, use the config:debug command.
drupal config:debug welcome.adminsettingsThe configuration name is welcome.adminsettings. You should see:
welcome_message: 'Welcome to the site'Display the Configured Message: Implement the hook_user_login() in welcome.module to display the message on user login.
/**
* Implements hook_user_login().
*/
function welcome_user_login($account) {
$config = \Drupal::config('welcome.adminsettings');
drupal_set_message($config->get('welcome_message'));
}After completing these steps, logging out and back in should display the welcome message.
This guide ensures you can easily create and configure an admin form in Drupal, enhancing the user experience by displaying custom messages on login.