Skip to content

Instantly share code, notes, and snippets.

@slattery
Forked from edutrul/mymodule--feature.js.js
Created August 12, 2022 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slattery/386770462c93c63c6883757e8ca7e103 to your computer and use it in GitHub Desktop.
Save slattery/386770462c93c63c6883757e8ca7e103 to your computer and use it in GitHub Desktop.
How to add javascript by using drupal 8 libraries using Drupalsettings(to pass php(backend) variables to js(frontend). This can be applied to files: ".theme", ".module"m "field formatter class", "views field handler", etc files. Also uses javascript drupal behaviours (great practice in D8) Plus contains "once" which only enables to execute one t…
// File js/mymodule--feature.js
(function ($) {
Drupal.behaviors.mymodule__feature = {
attach: function (context, drupalSettings) {
// Use once to avoid tu call multiple times a js.
$(document).once('feature').on('click', '.button--feature', (function (event) {
event.preventDefault();
if (typeof drupalSettings.mymodule.feature.id != 'undefined') {
console.log('Your great logic goes here and will NOT be called multiple times');
}
}));
},
};
})(jQuery);
hellosign:
js:
js/mymodule--feature.js: {}
dependencies:
- core/jquery
# In order to call $(document).once(
- core/jquery.once
- core/drupal
# In order to pass values from php (backend) to js (frontend).
- core/drupalSettings
<?php
/**
* Implements hook_preprocess_page().
*/
function THEME_NAME_preprocess_page(&$variables) {
$variables['#attached']['library'][] = 'mymodule/feature';
$variables['#attached']['drupalSettings']['mymodule']['feature'] = [
'id' => $this->credentials['id'],
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment