Search code examples
phpdrupaldrupal-7

Drupal 7: How to save form values with system_settings_form()?


I want to set up a simple settings form for a module I am building.

Currently I have just a fieldset and a single check box:

function my_module_settings() {
  $form = array();

  $config = my_module_default_settings();

  $form['my_module_settings'] = [
    '#type' => 'fieldset',
    '#title' => t('Script options'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#group' => 'script_config',
  ];

  $form['my_module_settings']['my_module_setting_scripts'] = array(
    'script_on' => array(
      '#type' => 'checkbox',
      '#title' => t('Enable Scripts'),
      '#default_value' => !empty($config['script_on']) ? $config['script_on'] : FALSE,
      '#group' => 'script_config',
    ),
  );

  return system_settings_form($form);
}

This does render, but checking the checkbox and hitting save does not actually save anything in the form.

How can I make sure my form data saves?


Solution

  • When using system_settings_form(), form data are saved in the {variable} database table, using form keys to name variables.

    When the form is submitted, the system_settings_form submit handler won't use 'script_on' but the form key.

    This function adds a submit handler and a submit button to a form array. The submit function saves all the data in the form, using variable_set(), to variables named the same as the keys in the form array. Note that this means you should normally prefix your form array keys with your module name, so that they are unique when passed into variable_set().

    This allows to use variable_get('form_key') to grab form data, meaning in your case you can directly map things like :

    '#default_value' => variable_get('my_module_setting_scripts', !!$config['script_on']);
    

    .. here with a ternary expression 'shortcut' (!!) for the fallback setting.