2

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:
testing.info
testing.module
js/mask.js

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';
}

Question:
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?

5
  • What hook are you using?
    – No Sssweat
    Commented Feb 28, 2018 at 21:54
  • @NoSssweat I'm using hook_init. it's function testing_init() { }
    – CocoSkin
    Commented Feb 28, 2018 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
    Commented Feb 28, 2018 at 22:54
  • @NoSssweat it's workings :)
    – CocoSkin
    Commented Mar 1, 2018 at 13:49
  • @NoSssweat is it possible only load for add/edit node and webform(not search form)?
    – CocoSkin
    Commented Mar 1, 2018 at 14:55

1 Answer 1

2

@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 and acknowledge you have read our privacy policy.

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