Drupal 8: Enable themes when a module gets enabled
07/10/2019 by Capy

Front.id

When you enable a Drupal module or profile, it may be useful to activate and set a theme for the end user and/or Drupal administration.

For this type of situations I leave you a snippet of code that is placed in the hook_install() of some module of your own that you have out there:

function foo_install() {
  $theme_list = [
    'stark',
    'adminimal_theme',
  ];

  // Install themes.
  \Drupal::service('theme_installer')->install($theme_list);

  // Get theme manager
  $system_theme = \Drupal::configFactory()->getEditable('system.theme');

  // Set default and admin themes.
  $system_theme
    ->set('default', 'stark')
    ->set('admin', 'adminimal_theme')
    ->save();
}

 

And that's it. When you activate the module "stark" will be activated for the end user and "adminimal_theme" for the admin part.

NOTE: This code logically works also in the hook_update_N() and hook_uninstall().

Bye!

Add new comment

The content of this field is kept private and will not be shown publicly.

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.