Drupal 8 - system settings form

Submitted by superadmin on Sun, 12/27/2015 - 15:22

system_settings_form was a handy function in Drupal 7 that saved forms to variables. This has been replaced by ConfigFormBase in Drupal 8. 

If we want the same behavior in Drupal 8 that was present in system_settings_form, our form class must extend ConfigFormBase. In doing so we must implement the abstract getEditableConfigNames method which returns the config names which are editable.

Also our buildForm method should call it's parent buildForm so that the submit buttons can be added.


namespace Drupal\example_module\Forms;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class StudentConfigForm extends ConfigFormBase {
  // The Form ID that is used in alter hooks.
  public function getFormId() {
    return 'student_config_form';
  // Configuration names that will be editable
  public function getEditableConfigNames() {
    return ['example_module.student'];

  public function buildForm(array $form, FormStateInterface $form_state, $args = '' ){
    $config = $this->config('example_module.student');
    $values = $config->get();
    $form['student'] = array(
      '#type' => 'details',
      '#title' => $this->t('Student'),
      '#open' => TRUE,
      '#tree' => TRUE,
    $form['student']['first_name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('First name'),
      '#default_value' => $values['student']['first_name']
    $form['student']['last_name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Job title'),
      '#default_value' => $values['student']['last_name']
    $form['student']['age'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Age'),
      '#default_value' => $values['student']['age']
    return parent::buildForm($form, $form_state);

  public function submitForm(array &$form, FormStateInterface $state) {
    $values = $state->getValues();
    $config = $this->config('example_module.student')
      ->set('student', $values['student'])

In our submitForm method when calling $this->config(..) we need to pass one the values we returned in getEditableConfigNames

You can see views doing the same for it's views ui config.

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.