On this page
ConfigFormBase with Simple Configuration API
This type of form is used to create forms for configuration pages on your Drupal website. You can set up configuration forms that allow you to make changes to features or views or other configuration entities.
Configuration forms can greatly help you to understand the workings of the Simple Configuration API for Drupal 8. In Drupal 8, you do not use the {variables} table and variable_get/set/delete() because configuration is stored in the database and synced with YML files on the disk for deployment purposes. It is possible to disable use of the database for config storage entirely but it comes with a performance hit with most filesystems.
The Simple Configuration API enables using objects like $config objects to communicate with a YML file. The $config object handles CRUD (Create/Read/Update/Delete) for YML files, so you simply use ::get(), ::set(), and ::save() methods and your data will be stored in the {module}.settings.yml file.
Example
1. In your_module.info.yml file, you define the configuration route:
...
configure: your_module.admin_settings
2. In your_module.routing.yml file, you define the route:
...
your_module.admin_settings:
path: '/admin/config/your_module'
defaults:
_form: '\Drupal\your_module\Form\ModuleConfigurationForm'
_title: 'your_module configuration screen'
requirements:
_permission: 'administer site configuration'
3. in your_module/src/Form/ModuleConfigurationForm.php you define the form:
<?php
namespace Drupal\your_module\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Defines a form that configures your_module’s settings.
*/
class ModuleConfigurationForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'your_module_admin_settings';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'your_module.admin_settings',
];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('your_module.admin_settings');
$form['your_message'] = [
'#type' => 'textfield',
'#title' => $this->t('Your message'),
'#default_value' => $config->get('your_message'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->config('your_module.admin_settings')
->set('your_message', $form_state->getValue('your_message'))
->save();
parent::submitForm($form, $form_state);
}
}
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion