0

How do I define a different administration theme for a user and administration role in Drupal 8?

I have looked at the context module for Drupal 8. There is a problem with the context condition and the reaction theme related items are all based on the front-end themes. I need the same but for the back-end themes.

My code is the same as the context reaction code for Theme.php. I just changed the submitConfiguration().

 /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $configuration['admin'] = $form_state->getValue('theme');
    $configuration += $this->getConfiguration();
      \Drupal::configFactory()
          ->getEditable('system.theme')
          ->set('admin', $form_state->getValue('theme'))
          ->save();
    $this->setConfiguration($configuration);
  }

I defined the following in the context configuration.

  1. Condition => Role:User

    Reaction => Admin Theme: Customtheme

  2. Condition => Role: Administrator

    Reaction => Admin Theme: Seven

Is this possible? Are there other methods for achieving this goal?

2 Answers 2

3

As the context module is still in alpha I would try a solution in custom code by extending the class AdminNegotiator:

src/Theme/CustomAdminNegotiator.php

<?php

namespace Drupal\mymodule\Theme;

use Drupal\user\Theme\AdminNegotiator;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAdminNegotiator extends AdminNegotiator {

  public function determineActiveTheme(RouteMatchInterface $route_match) {
    if (in_array('custom_role', $this->user->getRoles())) {
      return 'custom_admin_theme';
    }
  }

}

and register this service class in mymodule.services.yml tagged as theme negotiator with a priority higher than the default admin negotiator (-40):

services:
  theme.negotiator.admin_theme.custom:
    class: Drupal\mymodule\Theme\CustomAdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -39 }

The applies() method is kept the same as in AdminNegotiator, so that only users with the correct permission have access to this theme and this only applies for admin routes.

4

I came here just looking for a solution on how to programmatically set the admin theme (say during hook_install or hook_update).

This code will achieve that:

// Make sure the theme is installed
$theme_handler = \Drupal::service('theme_handler');
$theme_handler->install(['my_custom_admin_theme']);

// Set it as the admin theme
$config = \Drupal::service('config.factory')->getEditable('system.theme');
$config->set('admin', 'my_custom_admin_theme')->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.