Drupal.ajax.prototype.beforeSubmit - a lesser-known bit of usefulness

The problem

So you have a Drupal 7 AJAX form (this not tested on D8 yet) with more than one submit button. For whatever reason, you want to override one of the field values if a certain submit button is clicked. You can't easily add a click event handler to the submit button because Drupal AJAX does its own thing.

The solution?

There is a lesser-known handler mentioned in misc/ajax.js - Drupal.ajax.prototype.beforeSubmit. For reference the D7 source code is:

/**
 * Modify form values prior to form submission.
 */
Drupal.ajax.prototype.beforeSubmit = function (form_values, element, options) {
  // This function is left empty to make it simple to override for modules
  // that wish to add functionality here.
};

However documentation is sparse - several mentions of it around the web but I couldn't find any actual examples of changing a form field value using it. So here is one, where the button id is "edit-refine-button" and the field to override (which in my real-life example was a SELECT field) has id attribute "edit-fixed-duration" and name attribute "fixed_duration". (There may be a more elegant way of finding the form value item in the "form_values" array of objects):

Drupal.ajax['edit-mysubmit-button'].beforeSubmit = function (form_values, element, options) {
  form_values.forEach(formField => {
    if (formField.name == 'fixed_duration') {
      formField.value = '100';
    }
  });
  return true;
};


Note! that final return true; may make the difference between the AJAX call completing successfully or not.