Formulario de configuración en Drupal 8

Use $config in Form Context

You can use configuration forms to figure out how $config can grab the data entered by the user and change the data in the {module}.settings.yml file. Here is the code to declare a $config object in the form, which you can find in Form Settings PHP file.

The Drupal Core ConfigFactory class is a way to read and write configuration data, and it is used to instantiate a Config object based on the contents of a specified configuration file. The new Config object can then be used to perform CRUD operations on that data.

$Config Object with Form

Form definition example (located at hello/src/HelloSettingsForm.php) :

<?php
/**
 * @file
 * Contains \Drupal\hello\helloSettingsForm
 */
namespace Drupal\hello;

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

/**
 * Configure hello settings for this site.
 */
class helloSettingsForm extends ConfigFormBase {
 
/**
   * {@inheritdoc}
   */
 
public function getFormId() {
    return
'hello_admin_settings';
  }

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

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

   
$form['hello_thing'] = array(
     
'#type' => 'textfield',
     
'#title' => $this->t('thing'),
     
'#default_value' => $config->get('things'),
    ); 

    return
parent::buildForm($form, $form_state);
  }

 
/**
   * {@inheritdoc}
   */
 
public function submitForm(array &$form, FormStateInterface $form_state) {
   
$this->config('hello.settings')
      ->
set('things', $form_state->getValue('hello_thing'))
      ->
save();

   
parent::submitForm($form, $form_state);
  }
}
?>

Routing file (hello.routing.yml) :

hello.settings:
  path: '/admin/structure/hello/settings'
  defaults:
    _form: '\Drupal\hello\HelloSettingsForm'
    _title: 'Hello'
  requirements:
    _permission: 'administer site configuration'

Using the Config object, you can simplify your data collected from the form. Having the above code in your Form Settings file, you will be able to store form data in {module}.settings.yml.

Any class that extends ConfigFormBase must implement the method getEditableConfigNames and return an array of the names of the configuration fields that it edits.