I'm trying to attach a js file to a form using hook_form_alter() but I don't want to js to be loaded on the administration template.

How can I achieve something like this? With what do I need to replace the THEME != ADMINTHEME part in the following code snippet?

 * Implements hook_form_alter().
function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (($form_id == 'node_CUSTOM_edit_form' || $form_id == 'node_CUSTOM_form') && THEME !== ADMINTHEME) {
    $form['#attached']['library'][] = 'MYMODULE/myLib';
  • 2
    Does this answer your question? How to test if current page is an admin page? – leymannx Apr 29 '20 at 14:26
  • 1
    Just add an not-operator in front of \Drupal::service('router.admin_context')->isAdminRoute(). Like if (!\Drupal::service('router.admin_context')->isAdminRoute()) { ... }. – leymannx Apr 29 '20 at 14:28
  • (You also need to pay attention to your if-request. I edited your question to wrap the two form ID parts in an extra set of brackets to make sense. You could also use in_array() for that.) – leymannx Apr 29 '20 at 14:34
  • 3
    If this is for the public facing theme, why not do it in the theme itself rather than a module? – Alfred Armstrong Apr 29 '20 at 16:02
  • Thank you leymannx for your suggestion. I've seen that answer and tried to make it work but it only obliges to one condition or the other (it doesn't work when I check for both my node form && not the admin theme). Alfred Armstrong - thanks. This solved my issue but did not necessarily answer the question in the first place. – Florin Simion Apr 30 '20 at 8:31

To answer your question, you can get the active theme name using below code in module file.

$activeTheme = \Drupal::service('theme.manager')->getActiveTheme()->getName()

and check if $activeTheme !== 'Your admin theme'.

Recommended way:

In your case as you want to add library specific to theme, it should be added in theme file and not module file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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