Code example

Last updated on
30 April 2025

You are browsing documentation for an older version of Drupal, which is not supported any longer, and the information may not be correct. See current documentation for Contributed modules

Code example for developers to add UI configurable CSS to their project using the Style Settings module.

Alternatively to copy/pasting the code below, you can take a look at how things are done in the module's demo at 'sites/all/modules/style_settings/demo', which includes also an example of a 'preview area' to make style changes visible in the settings form itself. Furthermore it offers an image URL field with optional file upload, where as the example below only uses a URL field. The mentioned demos are made for a module. There is also a #2548427: Demo for theme settings.

Put the following comment at the top of your CSS files that contain variables:

/**
 * The CSS values that are wrapped in '/*variable' comments are intended for use
 * by https://www.drupal.org/project/style_settings. Enable that module to
 * have those CSS variables exposed in the settings UI.
 */

 
An example for FOO.admin.inc:

Replace FOO with your module's machine name.

<?php
/**
 * @file
 * The admin settings for the FOO module.
 */
/**
 * Implements hook_settings().
 */

function FOO_admin_settings() {
  // Put CSS variables together in a fieldset. Remove if only one is given.
  $form['css_variables'] = array(
    '#type' => 'fieldset',
    '#title' => t('CSS variables'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  if (module_exists('style_settings')) {
    // When we have a list of CSS variables it is better to collapse it.
    $form['css_variables']['#collapsed'] = TRUE;
    //
    // Any normal form API type can be used 
    // A normal TEXTFIELD. It does not offer any validation by itself.
    $form['css_variables']['FOO_caption_align'] = array(
      '#type' => 'textfield',
      '#title' => t('Caption text align'),
      '#default_value' => variable_get('FOO_caption_align', 'center'),
      '#size' => 12,
    );
    //
    // The Style Settings module offers several form API elements to help
    // developers build the settings page. Cool UI widgets and built-in
    // validation of user input especially designed for CSS attributes.
    //
    // NUMBER example in this case with an appended measurement unit (optional).
    // E.g. user input: '2', field_suffix: 'px' => stored variable: '2px'.
    $form['css_variables']['FOO_borderwidth'] = array(
      '#type' => 'style_settings_number',
      '#title' => t('Border width'),
      '#step' => 1, // In this case if forces an integer as input.
      '#min' => 0, // Could be omitted. Defaults to 0. Set to NULL to ignore.
      '#max' => 10, // Defaults to 1 if omitted.
      // The variable default should include a measurement unit if applicable.
      // Wrapped in floatval() to turn it into a number. E.g. '2px' => '2'.
      '#default_value' => floatval(variable_get('FOO_borderwidth', '2px')),
      // The suffix gets added to the input on submit if valid measurement unit.
      '#field_suffix' => 'px',
      // Uncomment the line below to NOT align the field input on the right.
//      '#attributes' => NULL,
      // Uncomment the line below to NOT show min, max and step values as help.
//      '#input_help' => NULL,
    );
    //
    // COLOR PICKER example.
    $form['css_variables']['FOO_bordercolor'] = array(
      '#type' => 'style_settings_colorpicker',
      '#title' => t('Border color'),
      // Besides hex color value also color names are accepted.
      '#default_value' => variable_get('FOO_bordercolor', 'IndianRed'),
    );
    //
    // SLIDER WIDGET example.
    $form['css_variables']['FOO_magnifier_icon_opacity'] = array(
      '#type' => 'style_settings_slider',
      '#title' => t('Magnifier icon opacity'),
      '#description' => t('0 = transparent. 1 = opaque.'),
      // The variable default should include a measurement unit if applicable.
      // Wrapped in floatval() to turn it into a number. E.g. '2px' => '2'.
      '#default_value' => floatval(variable_get('FOO_magnifier_icon_opacity', 0.85)),
      // Parameters below could be omitted. It is already preset for opacity.
      '#step' => 0.01,
      '#min' => 0,
      '#max' => 1,
      // The suffix gets added to the input on submit if valid measurement unit.
      // Added for demonstration purpose only.
      'field_suffix' => NULL,
    );
    //
    // IMAGE URL example.
    $form['css_variables']['FOO_bgimage'] = array(
      '#type' => 'style_settings_imgurl',
      '#title' => t('Background image'),
      // If you use this for a 'theme', replace 'module' below.
      '#default_value' => variable_get('FOO_bgimage', '/' . drupal_get_path('module', 'image') . '/sample.png'),
      // In the submit handler below we reset an empty field to the default URL.
      // This way the user isn't required to know the URL of the default image.
      '#description' => t('An absolute (external) or relative (local) image URL. A relative URL must be given from the base URL (<em>/sites/..</em>). Leave empty to reset to the default image.'),
    );
    //
    // A SELECTABLE MEASUREMENT UNIT (e.g. px, em, %) example. It goes together
    // with a submit handler inside the function FOO_admin_settings_submit().
    $form['css_variables']['FOO_fontsize'] = array(
      '#type' => 'fieldset', 
      '#title' => t('Caption font-size'),
      // Make containing fields align horizontally.
      '#attributes' => array('class' => array('container-inline')),
      // Add optionally a field description in the fieldset. NOT in the elements below.
      // Number field input help (min, max, step) will optionally be appended.
      '#description' => t('Note: A minimum font-size setting of your browser might interfere.'),
    );
    // Number field without a '#field_suffix'.
    $form['css_variables']['FOO_fontsize']['FOO_fontsize_value'] = array(
      '#type' => 'style_settings_number',
      '#default_value' => variable_get('FOO_fontsize_value', '85'),
      // Uncomment the line below to NOT show min, max and step values as help.
//      '#input_help' => NULL,
    );
    // A measurement unit select field.
    $form['css_variables']['FOO_fontsize']['FOO_fontsize_unit'] = array(
      '#type' => 'select',
      '#options' => array(
        'px' => t('px'),
        'em' => t('em'),
        '%' => t('%'),
      ),
      '#default_value' => variable_get('FOO_fontsize_unit', '%'),
      '#required' => TRUE,
    );
  }
  //
  // If the Style Settings module is not enabled, provide some instructions.
  else {
    $style_settings_module = l(t('Style (CSS) Settings module'), 'https://drupal.org/project/style_settings', array(
        'attributes' => array(
          'title' => t('Style (CSS) Settings | Drupal.org'),
          'target' => '_blank',
        ),
    ));
    $form['css_variables']['FOO_note'] = array(
      '#markup' => t("Enable the !style_settings_module to get style options exposed here. They consist of:<ul>
          <li> A caption font-size.</li>
          <li> ... </li>
          <li> ... </li>
        </ul>", array('!style_settings_module' => $style_settings_module)),
    );
  }
  //
  // Call submit_function() on form submission.
  $form['#submit'][] = 'FOO_admin_settings_submit';
  return system_settings_form($form);
}
/**
 * Submit form data.
 */
function FOO_admin_settings_submit($form, &$form_state) {
  if (module_exists('style_settings')) {
    // IMAGE URL: Reset to default if empty. Does not work after a hook_form_FORM_ID_alter().
    // In that case move it to the submit handler after hook_settings() in the 'parent' form.
    if (trim($form_state['values']['FOO_bgimage']) == '') {
      $form_state['values']['FOO_bgimage'] = '/' . drupal_get_path('module', 'image') . '/sample.png';
      drupal_set_message(t('The image URL has been reset to the default.'), 'warning', FALSE);
    }
    //
    // SELECTABLE MEASUREMENT UNIT: concatenate the value and unit in a new
    // variable (the one that will be used in the CSS).
    variable_set('FOO_fontsize', $form_state['values']['FOO_fontsize_value'] . $form_state['values']['FOO_fontsize_unit']);
    //
    // Make sure changes are visible right after saving the settings.
    _drupal_flush_css_js();
   }
}
?>

 
Note in the form submit handler:

_drupal_flush_css_js();

This way changes are visible right away after saving the form. Otherwise it is necessary to clear the cache after changing CSS variables at:
'/admin/config/development/performance'

The code above provides a working example of most style settings. However if you copy/paste this in a new FOO.admin.inc file, declare it in your FOO.module file :

<?php
/**
 * Implements hook_menu().
 */
function FOO_menu() {
  // Here placed in the 'config/SYSTEM' section. Put it in the appropriate section.
  $items['admin/config/system/FOO'] = array(
    'title' => 'FOO',
    'description' => 'FOO settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('FOO_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'FOO.admin.inc',
  );
  return $items;
}
?>

And don't forget to provide hook_uninstall in FOO.install to cleanup the created variables:

<?php
/**
 * @file
 * Sets post-install messages and deletes variables when uninstalled.
 */

/**
 * Implements hook_install().
 */
function style_settings_demo_install() {
  $t = get_t();
  $text = $t('Go and checkout the !config_link.', array(
    '!config_link' => l($t('Style Settings demo page'), 'admin/config/system/FOO'),
  ));
  drupal_set_message($text);
  _drupal_flush_css_js();
}

/**
 * Implements hook_uninstall().
 */
function style_settings_demo_uninstall() {
  // Delete all variables set in variable table.
  variable_del('FOO_bgimage');
  variable_del('FOO_magnifier_icon_opacity');
  variable_del('FOO_fontsize_value');
  variable_del('FOO_fontsize_unit');
  variable_del('FOO_fontsize');
  variable_del('FOO_caption_align');
  variable_del('FOO_borderwidth');
  variable_del('FOO_bordercolor');
  _drupal_flush_css_js();
}
?>

 


Help improve this page

Page status: Not set

You can: