Chris@0: /** Chris@0: * @file Chris@0: * System behaviors. Chris@0: */ Chris@0: Chris@17: (function($, Drupal, drupalSettings) { Chris@0: // Cache IDs in an array for ease of use. Chris@0: const ids = []; Chris@0: Chris@0: /** Chris@0: * Attaches field copy behavior from input fields to other input fields. Chris@0: * Chris@0: * When a field is filled out, apply its value to other fields that will Chris@0: * likely use the same value. In the installer this is used to populate the Chris@0: * administrator email address with the same value as the site email address. Chris@0: * Chris@0: * @type {Drupal~behavior} Chris@0: * Chris@0: * @prop {Drupal~behaviorAttach} attach Chris@0: * Attaches the field copy behavior to an input field. Chris@0: */ Chris@0: Drupal.behaviors.copyFieldValue = { Chris@0: attach(context) { Chris@0: // List of fields IDs on which to bind the event listener. Chris@0: // Create an array of IDs to use with jQuery. Chris@17: Object.keys(drupalSettings.copyFieldValue || {}).forEach(element => { Chris@14: ids.push(element); Chris@14: }); Chris@14: Chris@0: if (ids.length) { Chris@0: // Listen to value:copy events on all dependent fields. Chris@0: // We have to use body and not document because of the way jQuery events Chris@0: // bubble up the DOM tree. Chris@17: $('body') Chris@17: .once('copy-field-values') Chris@17: .on('value:copy', this.valueTargetCopyHandler); Chris@0: // Listen on all source elements. Chris@17: $(`#${ids.join(', #')}`) Chris@17: .once('copy-field-values') Chris@17: .on('blur', this.valueSourceBlurHandler); Chris@0: } Chris@0: }, Chris@0: detach(context, settings, trigger) { Chris@0: if (trigger === 'unload' && ids.length) { Chris@17: $('body') Chris@17: .removeOnce('copy-field-values') Chris@17: .off('value:copy'); Chris@17: $(`#${ids.join(', #')}`) Chris@17: .removeOnce('copy-field-values') Chris@17: .off('blur'); Chris@0: } Chris@0: }, Chris@0: Chris@0: /** Chris@0: * Event handler that fill the target element with the specified value. Chris@0: * Chris@0: * @param {jQuery.Event} e Chris@0: * Event object. Chris@0: * @param {string} value Chris@0: * Custom value from jQuery trigger. Chris@0: */ Chris@0: valueTargetCopyHandler(e, value) { Chris@0: const $target = $(e.target); Chris@0: if ($target.val() === '') { Chris@0: $target.val(value); Chris@0: } Chris@0: }, Chris@0: Chris@0: /** Chris@0: * Handler for a Blur event on a source field. Chris@0: * Chris@0: * This event handler will trigger a 'value:copy' event on all dependent Chris@0: * fields. Chris@0: * Chris@0: * @param {jQuery.Event} e Chris@0: * The event triggered. Chris@0: */ Chris@0: valueSourceBlurHandler(e) { Chris@0: const value = $(e.target).val(); Chris@0: const targetIds = drupalSettings.copyFieldValue[e.target.id]; Chris@0: $(`#${targetIds.join(', #')}`).trigger('value:copy', value); Chris@0: }, Chris@0: }; Chris@17: })(jQuery, Drupal, drupalSettings);