Last active
March 6, 2023 10:42
-
-
Save prashantdsala/88171b8a9d7eaedcedcb740a6e36e08c to your computer and use it in GitHub Desktop.
How to create your own custom settings form in Drupal
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
name: Custom Config Form | |
description: This module illustrates how to create your own config/settings form. | |
core_version_requirement: ^8 || ^9 || ^10 | |
type: module | |
configure: custom_config_form.settings |
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
custom_config_form.settings: | |
path: '/admin/config/system/settings' | |
defaults: | |
_title: 'Custom Settings Page' | |
_form: 'Drupal\custom_config_form\Form\SettingsForm' | |
requirements: | |
_permission: 'administer site configuration' |
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 | |
namespace Drupal\custom_config_form\Form; | |
use Drupal\Core\Form\ConfigFormBase; | |
use Drupal\Core\Form\FormStateInterface; | |
/** | |
* Configure Custom Config Form settings for this site. | |
*/ | |
class SettingsForm extends ConfigFormBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getFormId() { | |
return 'custom_config_form_settings'; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
protected function getEditableConfigNames() { | |
return ['custom_config_form.settings']; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function buildForm(array $form, FormStateInterface $form_state) { | |
$form['example'] = [ | |
'#type' => 'textfield', | |
'#title' => $this->t('Example'), | |
'#default_value' => $this->config('custom_config_form.settings')->get('example'), | |
]; | |
return parent::buildForm($form, $form_state); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function validateForm(array &$form, FormStateInterface $form_state) { | |
if ($form_state->getValue('example') != 'example') { | |
$form_state->setErrorByName('example', $this->t('The value is not correct.')); | |
} | |
parent::validateForm($form, $form_state); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function submitForm(array &$form, FormStateInterface $form_state) { | |
$this->config('custom_config_form.settings') | |
->set('example', $form_state->getValue('example')) | |
->save(); | |
parent::submitForm($form, $form_state); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment