My idea:
I am trying to use a module to manage all the js and css with #attached method.
#attached method I found from:
- Adding CSS and JS to form with attachments
- https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

My module folder containing:

In testing.info, it's including file testing.module
files[] = testing.module

In testing.module, I'm trying to use the #attached method to attach "jquery mask" to all form tags, including add/edit node, webform field.
Here is my code but it does not work. -___-

function testing_init() {
  $build['#attached']['js']['https://cdn.testing.com/jquery.mask.min.js'] = array('type' => 'external');
  $form['#attached']['js'][] = drupal_get_path('module', 'testing') . '/js/mask.js';

Am I using the wrong method to attach js to form tag?
I don't want to load these files on all pages, what is the better way?

  • What hook are you using? – No Sssweat Feb 28 '18 at 21:54
  • @NoSssweat I'm using hook_init. it's function testing_init() { } – CocoSkin Feb 28 '18 at 22:00
  • 1
    well $form['#attached']['js'][] = drupal_get_path('module', 'testing') . '/js/mask.js'; is never going to work inside of hook_init. Use hook_form_alter testing_form_alter(&$form, &$form_state, $form_id) { remember to flush cache after to see changes. – No Sssweat Feb 28 '18 at 22:54
  • @NoSssweat it's workings :) – CocoSkin Mar 1 '18 at 13:49
  • @NoSssweat is it possible only load for add/edit node and webform(not search form)? – CocoSkin Mar 1 '18 at 14:55

@NoSssweat is it possible only load for add/edit node and webform(not search form)? – CocoSkin

You can by utilizing hook_form_BASE_FORM_ID_alter

For node's add/edit form:

 *  Implements hook_form_BASE_FORM_ID_alter.
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/custom.js';

For Webform:

 *  Implements hook_form_BASE_FORM_ID_alter.
function mymodule_form_webform_client_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/custom.js';

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.