system.es6.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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').once('copy-field-values').on('value:copy', this.valueTargetCopyHandler);
  32. // Listen on all source elements.
  33. $(`#${ids.join(', #')}`).once('copy-field-values').on('blur', this.valueSourceBlurHandler);
  34. }
  35. },
  36. detach(context, settings, trigger) {
  37. if (trigger === 'unload' && ids.length) {
  38. $('body').removeOnce('copy-field-values').off('value:copy');
  39. $(`#${ids.join(', #')}`).removeOnce('copy-field-values').off('blur');
  40. }
  41. },
  42. /**
  43. * Event handler that fill the target element with the specified value.
  44. *
  45. * @param {jQuery.Event} e
  46. * Event object.
  47. * @param {string} value
  48. * Custom value from jQuery trigger.
  49. */
  50. valueTargetCopyHandler(e, value) {
  51. const $target = $(e.target);
  52. if ($target.val() === '') {
  53. $target.val(value);
  54. }
  55. },
  56. /**
  57. * Handler for a Blur event on a source field.
  58. *
  59. * This event handler will trigger a 'value:copy' event on all dependent
  60. * fields.
  61. *
  62. * @param {jQuery.Event} e
  63. * The event triggered.
  64. */
  65. valueSourceBlurHandler(e) {
  66. const value = $(e.target).val();
  67. const targetIds = drupalSettings.copyFieldValue[e.target.id];
  68. $(`#${targetIds.join(', #')}`).trigger('value:copy', value);
  69. },
  70. };
  71. }(jQuery, Drupal, drupalSettings));