CSS code form for custom theme Drupal 9

Suppose we have a site on Drupal 9 with a custom theme, and because of some factors, you do not have the opportunity to connect on FTP to add code on the first occasion. In this case, we need to add a little code to our topic and we will be able to add CSS from the admin panel.

Suppose we already have a somewhat modified topic and has a setting file theme-settings.php

<?php

    function themename_form_system_theme_settings_alter(&$form, &$form_state) {
        $form['custom_css'] = [
            '#type' => 'textarea',
            '#title' => t('Custom CSS'),
            '#default_value' => theme_get_setting('custom_css'),
            '#description' => t('Enter custom CSS here.'),
        ];

        $form['#submit'][] = 'themename_form_system_theme_settings_submit';

    }

    function themename_form_system_theme_settings_submit($form, &$form_state) {
        $css_code = $form_state->getValue('custom_css');
        $file_path = DRUPAL_ROOT . '/themes/custom/themename/css/default.css';
        file_put_contents($file_path, "\n" . $css_code, FILE_APPEND);
    }
    

Here we first add to the settings page of your topic for a custom code. After, we add the function of storing the form data, which specify the path to the file of the style of our topic, at the end of which our custom code will be added.

Important note - depending on the settings of your site cache or server, changes in the browser may not appear immediately.

 

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.