How can you contact us

2By phone at +40 749 014 360

If you still have problems, please let us know, by sending an email to info@westweb-solutions.com Thank you!

OFFICE HOURS

Mon-Fri 9:00AM - 6:00AM
Sat - 9:00AM - 1:00PM
Sundays by appointment only!

Drupal 8 - How to create a simple config form

/ / Drupal 8

To create a configuration form, we need to extend our form from ConfigFormBase and not from FormBase like we do in case of a normal form.

Extending the ConfigFormBase, we need also to implement the getEditableConfigNames() method, that will return an array with condiguration names that are editable.

In the buildForm() method, we need to create all form elements that will be used to input the settings. For this, we can use the form API of Drupal 8.

Of course, we can have access to our configuration object and get all our configurations from it.

A very important here, would be to call the parent's buildForm() method to let Drupal process the form correctly.


namespace Drupal\example\Form;

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

/**
 * Class ExampleConfigurationForm.
 *
 * @package Drupal\example\Form
 */
class ExampleConfigurationForm extends ConfigFormBase {

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Get our configuration object.
    $config = $this->config('example.settings');

    // Use the form API to add form elements.
    $form['your_global_message'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Your global message'),
      '#default_value' => $config->get('your_global_message'),
    );

    // Call the build
    return parent::buildForm($form, $form_state);
  }
}


In our submitForm() method, we need to save the configuration to our configuration object.


  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    // Save the settings.
    $this->config('example.settings')
      ->set('your_global_message', $values['your_global_message'])
      ->save();
  }


That's it :)

Sign in your account to have access to different features

Forgot your details?

TOP