Jun 04, 2019 in Drupal 8, Snippets

The following code shows how to create a custom form in the drupal back-end and how to save custom config defined in your custom module. Powerful stuff and very flexible.

You can update custom config with a settings form you build. 
In a custom module *custom_mailing* add a file called *custom_mailing.routing.yml* add the following route:

custom_mailing.route_admin_settings:
  path: '/admin/config/mailing'
  defaults:
    _title: 'Custom mailing'
    _form: '\Drupal\custom_mailing\Form\AdminSettingsForm'
  requirements:
    _permission: 'administer custom_mailing settings'

Now I want a boolean value to be editable. I create a file in a map `config/install` called *custom_mailings.settings.yml* with the following content:

mailsettings:
  enabled: 0

In a module called *custom_mailing*. Inside `src/Form` add file called `AdminSettingsForm.php`.

    <?php
    // snippet: https://stefvanlooveren.me/node/74

    namespace Drupal\custom_mailing\Form;
    
    use Drupal\Core\Form\ConfigFormBase;
    use Drupal\Core\Form\FormStateInterface;
    
    /**
     * Class AdminSettingsForm.
     *
     * @package Drupal\custom_mailing\Form
     */
    class AdminSettingsForm extends ConfigFormBase {
    
      /**
       * {@inheritdoc}
       */
      public function getFormId() {
        return 'custom_mailing_admin_settings_form';
      }
    
      /**
       * {@inheritdoc}
       */
      protected function getEditableConfigNames() {
        return [
          'custom_mailing.settings',
        ];
      }
    
      /**
       * {@inheritdoc}
       */
      public function buildForm(array $form, FormStateInterface $form_state) {
        $config = $this->config('custom_mailing.settings');
    
        $form['mailsettings'] = [
          '#tree' => TRUE,
          '#type' => 'fieldset',
          '#title' => $this->t('Email settings'),
        ];
    
        $form['mailsettings']['enabled'] = [
          '#type' => 'checkbox',
          '#title' => $this->t('Enable sending of e-mails.'),
          '#default_value' => $config->get('mailsettings.enabled'),
        ];
    
        return parent::buildForm($form, $form_state);
      }
    
      /**
       * {@inheritdoc}
       */
      public function submitForm(array &$form, FormStateInterface $form_state) {
        $config = $this->config('custom_mailing.settings');
        $config->set('mailsettings', $form_state->getValue('mailsettings'));
        $config->save();
        parent::submitForm($form, $form_state);
      }
    
    }

Now enable the module, clear cache and head to the url. You'll see your form. But more important, you can update the settings and export it later on to your configuration files. Nice!