Saving form data with config.factoryfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Continuing from our last discussion on post-submission redirects using setRedirect(), we now shift our attention to a critical aspect of Drupal development: saving form data with config.factory. This lesson will guide you through the process of leveraging Drupal's configuration management system to store and retrieve data effectively.

Understanding config.factory

The config.factory service in Drupal provides an organized way to handle configuration management. It is particularly useful for storing non-content settings that your module may require across sessions, such as site settings or form configurations that need to persist independently of individual user input sessions.

Benefits of Using config.factory

  • Persistence: Ensures that data is stored persistently across different user sessions.
  • Scalability: Supports efficient retrieval and storage of configuration data, making it ideal for extensive applications.
  • Centralized Management: Centralizes configuration data management, simplifying updates and consistency across environments.

Implementing config.factory to Save Data

Let’s create a form where user settings are saved using config.factory for retrieval later:

function mymodule_form(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $config = \Drupal::config('mymodule.settings');
  
  $form['greeting'] = [
    '#type' => 'textfield',
    '#title' => t('Greeting Message'),
    '#default_value' => $config->get('greeting') ?? 'Hello World!',
    '#required' => TRUE,
  ];

  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('Save'),
  ];

  return $form;
}

function mymodule_form_submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $greeting = $form_state->getValue('greeting');
  \Drupal::configFactory()->getEditable('mymodule.settings')
    ->set('greeting', $greeting)
    ->save();

  \Drupal::messenger()->addMessage(t('Settings have been saved successfully.'));
}
    

Here's a breakdown of this code:

  • The form retrieves the current greeting setting using \Drupal::config() and displays it as the default value.
  • Upon form submission, getEditable() is used to edit and persist the configuration data for the input received.

Creating the Configuration Schema

To manage configuration via the UI or exports, define a configuration schema in my_module.schema.yml:

mymodule.settings:
  type: config_object
  label: 'My Module Settings'
  mapping:
    greeting:
      type: string
      label: 'Greeting Message'
    

This schema tells Drupal how to handle the configuration object, supporting features such as configuration snapshots and translations.

Best Practices

  • Naming Consistency: Use consistent naming conventions for configuration objects to facilitate organization and retrieval.
  • Documentation: Thoroughly document configuration settings within the codebase for clarity and ease of maintenance.
  • Minimalism: Only store configurations that are truly necessary to avoid bloat and improve performance.

Conclusion

Saving form data using config.factory is an efficient way to handle data persistence in Drupal. This approach harnesses Drupal's built-in functionality to manage settings that are critical to your site's behavior and layout.

Coming Up: Creating or Updating Entities on Submission

Next, we’ll explore how to create or update entities within Drupal upon form submission. This technique is essential for dynamically managing content and data structures within your application. Stay with us for more in-depth insights!