[Drupal] How to add a custom admin settings form to accept variable values in Drupal?

| | 1 min read

Sometimes the best way to handle variable value changes on a Drupal site, would be with an admin settings form to show/edit the value. For example, while implementing a "send test mail" functionality on a Drupal site, we might want to set the recipient address at testing time. It would be easy to create an admin settings form instead of changing the addresses each time in code.

Code:

function hook_menu() {
  $menus['admin/settings/custom'] = array(
    'title' => 'Custom Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_admin_settings'),
    'access callback' => 'user_access',
    'access arguments' => array('access administration menu'),
  );
  return $menus;
}
function custom_admin_settings() {
  $form['recipient_address'] = array(
    '#type' => 'textfield',
    '#title' => t('Recipient email address'),
    '#default_value' => variable_get('recipient_address', ''),
  );
  return system_settings_form($form);
}

In this example, we saved the textfield value into the variable 'recipient_address', which in turn is stored in variable table.

We can now get this variable using

$address = variable_get('recipient_address', '');

Just to mention, this is how we would set a value to a variable by code:

variable_set('recipient_address', $recipient_address);