Drupal 7:如何使用 system_settings_form() 保存表单值?

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

我想为我正在构建的模块设置一个简单的设置表单。

目前我只有一个字段集和一个复选框:

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);
}

这确实呈现,但选中复选框并点击保存实际上并没有保存表单中的任何内容。

如何确保我的表单数据得到保存?

使用system_settings_form()时,表单数据保存在{variable}数据库table中,使用表单键命名变量。

提交表单时,system_settings_form 提交处理程序不会使用 'script_on',而是使用表单键。

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().

这允许使用 variable_get('form_key') 来获取表单数据,这意味着在您的情况下您可以直接映射:

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

.. 这里有一个三元表达式 'shortcut' (!!) 作为回退设置。