Skip to content

Instantly share code, notes, and snippets.

@edutrul
Last active August 12, 2022 19:11
Show Gist options
  • Save edutrul/f2e38caf5fe8ef448cac4725e97e1a28 to your computer and use it in GitHub Desktop.
Save edutrul/f2e38caf5fe8ef448cac4725e97e1a28 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