Created
October 12, 2022 19:31
-
-
Save jtarleton/76a45e29c5027fa6e879e20bb1a43daf to your computer and use it in GitHub Desktop.
Adding Additional Fields to a Drupal Core Form (or any Drupal form) Using hook_form_alter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* mymodule module file. | |
*/ | |
use Drupal\Core\Form\FormStateInterface; | |
/** | |
* Implements hook_form_alter(). | |
*/ | |
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) { | |
// Appends to the system - site information settings | |
if (str_contains('system_site_information_settings', $form_id)) { | |
// Add an additional site_login_blurb fields and | |
// save the values to system.site config. | |
// Read current config values for site_login_blurb settings. | |
$config = \Drupal::config('system.site'); | |
$form['site_information']['site_login_blurb'] = [ | |
'#type' => 'textarea', | |
'#title' => t('Login Blurb'), | |
'#default_value' => NULL !== $config->get('site_login_blurb') ? $config->get('site_login_blurb') : '', | |
'#description' => t("Optionally, enter blurb text to be displayed above the site login form."), | |
]; | |
$form['site_information']['site_login_blurb_display'] = [ | |
'#type' => 'checkbox', | |
'#title' => t('Display Blurb on Login Form'), | |
'#default_value' => NULL !== $config->get('site_login_blurb_display') ? $config->get('site_login_blurb_display') : '', | |
'#description' => t("If checked, display the login form blurb text."), | |
]; | |
// Append a submit handler to save custom blurb and checkbox value. | |
$form['#submit'][] = '_mymodule_set_site_login_blurb'; | |
} | |
} | |
/** | |
* Save the values to system.site config. | |
*/ | |
function _mymodule_set_site_login_blurb(array &$form, FormStateInterface $form_state) { | |
$config = \Drupal::getContainer()->get('config.factory')->getEditable('system.site'); | |
$config->set('site_login_blurb', $form_state->getValue('site_login_blurb')) | |
->set('site_login_blurb_display', $form_state->getValue('site_login_blurb_display')) | |
->save(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment