Drupal configuration form
Part IV of the Practical Guide to Creating Basic Drupal 8 Modules
From .info to Tests, Just the Basics
So far, everything is pretty tidy, but how can we change what we see? With some forms, of course.
For simple use cases, see the section on Site Settings and Labels.
/src/Form/LoremIpsumForm.php
<?php
namespace Drupal\loremipsum\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
class LoremIpsumForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'loremipsum_form';
}
We begin our settings file by extending ConfigFormBase. The LoremIpsumForm
class is the one referenced in the routing.yml
file.
Next comes the method that actually builds the settings form:
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Form constructor.
$form = parent::buildForm($form, $form_state);
// Default settings.
$config = $this->config('loremipsum.settings');
The $config
variable is where we store our current settings.
We then define our form fields and return the form:
// Page title field.
$form['page_title'] = array(
'#type' => 'textfield',
'#title' => $this->t('Lorem ipsum generator page title:'),
'#default_value' => $config->get('loremipsum.page_title'),
'#description' => $this->t('Give your lorem ipsum generator page a title.'),
);
// Source text field.
$form['source_text'] = array(
'#type' => 'textarea',
'#title' => $this->t('Source text for lorem ipsum generation:'),
'#default_value' => $config->get('loremipsum.source_text'),
'#description' => $this->t('Write one sentence per line. Those sentences will be used to generate random text.'),
);
return $form;
}
We also need to declare the validateForm()
, submitForm()
, and getEditableConfigNames()
methods, even if we’re not using them:
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$config = $this->config('loremipsum.settings');
$config->set('loremipsum.source_text', $form_state->getValue('source_text'));
$config->set('loremipsum.page_title', $form_state->getValue('page_title'));
$config->save();
return parent::submitForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'loremipsum.settings',
];
}
}
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.