Drupal - How do I add custom theme settings?

You can create new file and call it as theme-settings.php and add the following to it or even add this to THEME_NAME.theme file.

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Theme\ThemeSettings;
use Drupal\system\Form\ThemeSettingsForm;
use Drupal\Core\Form;

function THEME_NAME_form_system_theme_settings_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state) {
  $form['THEME_NAME_settings']['social_icon']['social_url'] = array(
    '#type' => 'textfield',
    '#title' => t('Social Link'),
    '#default_value' => theme_get_setting('social_url', 'THEME_NAME'),
  );
}

Then you need to add the following to THEME_NAME.theme file.

function THEME_NAME_preprocess_page(&$variables) {
  $variables['social_url'] = theme_get_setting('social_url','THEME_NAME');
}

Then you can use it in the twig file.

<a href="{{ social_url }}" class="btn-social btn-outline"><i class="fa fa-fw fa-facebook"></i></a>

To have a default value for the social url, you can include it in your config/install/THEME.settings.yml

Hope it helps!


Additional to Suresh's answer: If you want to have all theme settings available in your twig template, use the following function:

use Drupal\Core\Cache\CacheableMetadata;
function _THEME_extend_variables(&$variables){
  // Add cachability metadata.
  $theme_name = \Drupal::theme()->getActiveTheme()->getName();
  $theme_settings = \Drupal::config($theme_name . '.settings');
  CacheableMetadata::createFromRenderArray($variables)
    ->addCacheableDependency($theme_settings)
    ->applyTo($variables);
  // Union all theme setting variables to the twig template variables.
  $variables += $theme_settings->getOriginal();
}

and call it when ever you need to extend $variables:

function THEME_preprocess_page(&$variables) {
  // extend twig variables with theme settings
  _THEME_extend_variables($variables);
  // do fancy stuff
}

This is more or less copy pasted from basic theme.

Tags:

Forms

8