Last active
August 12, 2022 19:11
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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