1
<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter()
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'search_form') {

     $form['#attached']['library'][] = 'mymodule/mylibrary';

  }

}

Doing a dpm($form) on the search form, I see it has the my attached library, so what gives?


Solution:

The above code works fine, turns out it was my js code, I had copied over from another js file and it had an if statement that somehow I missed (it was 4 am). Credit @Alexei Rayu

  • Did you check using a different theme to see if you have a form alter at that level removing extra JS? Also did you do the basic cache rebuild (seems likely you did but always worth double checking)? – acrosman Jul 15 '16 at 20:07
  • I think the "solution" part of this question should be move to an additional answer (though the same info is also already include in your comment below the accepted answer,, so maybe its just redundant?) – Pierre.Vriens Jul 20 '16 at 6:10
  • @Pierre.Vriens yes, it would be redundant, I just added to the Q to not confuse future readers. – No Sssweat Jul 20 '16 at 6:18
  • Indeed ... like me. – Pierre.Vriens Jul 20 '16 at 7:14
2

In Drupal 8, you first need to define assets in a library in your theme or module: https://www.drupal.org/developing/api/8/assets

and then you can attach that library to your form like this:

$form['#attached']['library'][] = 'mymodule/mylibrary';
  • thx, but I've a .libraries.yml already. As mentioned in my Q, when I go to node/1/edit it works, ugh, I guess shouldn't have named it js on my example, my bad. – No Sssweat Jul 15 '16 at 10:30
  • The form has a different id on the search page. Check out if you need to adjust form identification. – Alexei Rayu Jul 15 '16 at 10:32
  • but I didn't specify an id, which means, it should apply to all forms, right? – No Sssweat Jul 15 '16 at 10:44
  • 1
    So the file DOES get loaded. Then, the problem is in the JS code. Should you add your JS code to the ticket? – Alexei Rayu Jul 15 '16 at 10:59
  • 1
    turns out it was my js code, I had copied over from another js file and it had an if statement that somehow I missed. Thx for your help! – No Sssweat Jul 15 '16 at 23:57

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.