system.es6.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * @file
  3. * System behaviors.
  4. */
  5. (function($, Drupal, drupalSettings) {
  6. // Cache IDs in an array for ease of use.
  7. const ids = [];
  8. /**
  9. * Attaches field copy behavior from input fields to other input fields.
  10. *
  11. * When a field is filled out, apply its value to other fields that will
  12. * likely use the same value. In the installer this is used to populate the
  13. * administrator email address with the same value as the site email address.
  14. *
  15. * @type {Drupal~behavior}
  16. *
  17. * @prop {Drupal~behaviorAttach} attach
  18. * Attaches the field copy behavior to an input field.
  19. */
  20. Drupal.behaviors.copyFieldValue = {
  21. attach(context) {
  22. // List of fields IDs on which to bind the event listener.
  23. // Create an array of IDs to use with jQuery.
  24. Object.keys(drupalSettings.copyFieldValue || {}).forEach(element => {
  25. ids.push(element);
  26. });
  27. if (ids.length) {
  28. // Listen to value:copy events on all dependent fields.
  29. // We have to use body and not document because of the way jQuery events
  30. // bubble up the DOM tree.
  31. $('body')
  32. .once('copy-field-values')
  33. .on('value:copy', this.valueTargetCopyHandler);
  34. // Listen on all source elements.
  35. $(`#${ids.join(', #')}`)
  36. .once('copy-field-values')
  37. .on('blur', this.valueSourceBlurHandler);
  38. }
  39. },
  40. detach(context, settings, trigger) {
  41. if (trigger === 'unload' && ids.length) {
  42. $('body')
  43. .removeOnce('copy-field-values')
  44. .off('value:copy');
  45. $(`#${ids.join(', #')}`)
  46. .removeOnce('copy-field-values')
  47. .off('blur');
  48. }
  49. },
  50. /**
  51. * Event handler that fill the target element with the specified value.
  52. *
  53. * @param {jQuery.Event} e
  54. * Event object.
  55. * @param {string} value
  56. * Custom value from jQuery trigger.
  57. */
  58. valueTargetCopyHandler(e, value) {
  59. const $target = $(e.target);
  60. if ($target.val() === '') {
  61. $target.val(value);
  62. }
  63. },
  64. /**
  65. * Handler for a Blur event on a source field.
  66. *
  67. * This event handler will trigger a 'value:copy' event on all dependent
  68. * fields.
  69. *
  70. * @param {jQuery.Event} e
  71. * The event triggered.
  72. */
  73. valueSourceBlurHandler(e) {
  74. const value = $(e.target).val();
  75. const targetIds = drupalSettings.copyFieldValue[e.target.id];
  76. $(`#${targetIds.join(', #')}`).trigger('value:copy', value);
  77. },
  78. };
  79. })(jQuery, Drupal, drupalSettings);