system.es6.js 2.5 KB

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