How to create or manage configuration form in Drupal 8


How to create or manage configuration form in Drupal 8
By: Anonymous | Published On: Wed, 05/26/2021 - 19:16

Create configuration form

create path in routing.yml, here my module name is "mymodule" so I am using it, you can use your module name.

I have created form "MyConfigurationForm.php" in folder src/Form

_permission: 'mymodule dashboard_admin' command is used to set permission for the rout path, We create a separate file  name "mymodule.permissions.yml"  where permission related code will be appear on URL based 


  path: 'myconf'
    _form: '\Drupal\mymodule\Form\MyConfigurationForm'	
    _title: 'My API Configuration'
    _permission: 'mymodule dashboard_admin'

I have added this code in MyConfigurationForm.php to save data, other codes will same which use to form like header file class etc.

Put the following code in MyConfigurationForm.php


    $form['my_token'] = [
      '#type' => 'textfield',
      '#title' => $this->t('My Token'),
      '#default_value' => $config->get('my_token'),

    $form['my_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('My Accress Key'),
      '#default_value' => $config->get('my_key'),

    return parent::buildForm($form, $form_state);

  // Here we are saving values in variables which will use later.
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve the configuration.
	// Set the submitted configuration setting.
      ->set('my_token', $form_state->getValue('my_token'))
      ->set('my_key', $form_state->getValue('my_key'))
    parent::submitForm($form, $form_state);

When you want to use this variable in other you can use this code

$config = \Drupal::config('Mytest.settings');

To get variable, it will return value which is stored in "my_token"

$my_token = $config->get('my_token'); 

Need Help ?