Skip to content

Instantly share code, notes, and snippets.

@prashantdsala
Last active March 6, 2023 10:42
Show Gist options
  • Save prashantdsala/88171b8a9d7eaedcedcb740a6e36e08c to your computer and use it in GitHub Desktop.
Save prashantdsala/88171b8a9d7eaedcedcb740a6e36e08c to your computer and use it in GitHub Desktop.
How to create your own custom settings form in Drupal
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
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'
<?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