logo

How to create or manage configuration form in Drupal 8

01
April

How to create or manage configuration form in Drupal 8
By: Anonymous | Published On: Thu, 04/01/2021 - 18:15

How to create or manage configuration form in Drupal 8


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.

mymodule.Myfiguration:
  path: 'myconf'
  defaults:
    _form: '\Drupal\mymodule\Form\MyConfigurationForm'	// I have created form "MyConfigurationForm.php" 
    _title: 'My API Configuration'
  requirements:
    _permission: 'mymodule dashboard_admin'		// this is permission setting which is setting in mymodule.permissions.yml

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

 

class MyConfigurationForm extends ConfigFormBase {

  /** 
   * Config settings.
   *
   * @var string
   */
  const SETTINGS = 'Mytest.settings';

  /** 
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'Mytest_settings';
  }

  /** 
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      static::SETTINGS,
    ];
  }

  /** 
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config(static::SETTINGS);

    $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);
  }

  /** 
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve the configuration.
	// Set the submitted configuration setting.
    $this->configFactory->getEditable(static::SETTINGS)
      ->set('my_key', $form_state->getValue('my_key'))
      ->set('my_token', $form_state->getValue('my_token'))
      ->save();

    parent::submitForm($form, $form_state);
  }

}

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

$config = \Drupal::config('Mytest.settings');	// "Mytest.settings" is contant which has been set in top in the form

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

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

Need Help ?