Skip to main content

Generate an admin form in Drupal 8

Updated by Tim Rabbetts on
macro, cogwheel, gear

The easiest way to start is to use the drupal console command to generate the admin form.

drupal generate:form:config

Most options are clear, I added an API key and secret field.  Important to give an admin path, in my case I used /admin/config/blue_lion/externalapikey.

Here is the form this command generated:

<?php

namespace Drupal\blue_lion\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class ExternalApiKeyForm.
 */
class ExternalApiKeyForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'blue_lion.externalapikey',
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('blue_lion.externalapikey');
    $form['api_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API Key'),
      '#maxlength' => 256,
      '#size' => 256,
      '#default_value' => $config->get('api_key'),
    ];
    $form['api_secret'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API Secret'),
      '#maxlength' => 256,
      '#size' => 256,
      '#default_value' => $config->get('api_secret'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    $this->config('blue_lion.externalapikey')
      ->set('api_key', $form_state->getValue('api_key'))
      ->set('api_secret', $form_state->getValue('api_secret'))
      ->save();
  }

}

We have a form with some fields, and on submit we store these values in the config for use later.

You will notice a router entry created too, _admin_route is essential!

blue_lion.external_api_key_form:
  path: '/admin/config/blue_lion/externalapikey'
  defaults:
    _form: '\Drupal\blue_lion\Form\ExternalApiKeyForm'
    _title: 'ExternalApiKeyForm'
  requirements:
    _permission: 'access administration pages'
  options:
    _admin_route: TRUE

Now if we got to the admin menu you will see there is an entry:

admin menu drupal 8

HINT: if you want to access these values somewhere else in code here is the best way.

$apiKey = \Drupal::config('blue_lion.externalapikey')->get('api_key');
$apiSecret = \Drupal::config('blue_lion.externalapikey')->get('api_secret');

 

Add new comment