Problem/Motivation
When processing an element for a Field widget, the widget has the ability to modify the wider form. $form is passed by reference into `formSingleElement` and `form` methods on WidgetBase.
This ability is not extended to to the `field_widget_complete_form` or `field_widget_single_element_form` (and accompanying TYPE hooks) because $form that is added to the provided $context array is not passed by reference:
if ($element) {
// Allow modules to alter the field widget form element.
$context = [
'form' => $form,
'widget' => $this,
'items' => $items,
'delta' => $delta,
'default' => $this->isDefaultValueWidget($form_state),
];
\Drupal::moduleHandler()->alter(['field_widget_single_element_form', 'field_widget_single_element_' . $this->getPluginId() . '_form'], $element, $form_state, $context);
}
This means that any third parth modifications to these widgets that need to add form submit callbacks or #process callback cannot do it.
Seeing as the ability to modify the $form is avalible to the Widget itself and that the alter hooks can modify $form_state already (because of the nature of objects), I would expect the ability to edit $form to be provided to the alter hooks as well.
Steps to reproduce
Add the following alter hook to a module. The form process callback will not be called.
function mymodule_field_widget_single_element_form_alter(&$element, FormStateInterface &$form_state, &$context) {
$form = &$context['form'];
$form['#process'][] = 'mymodule_field_widget_form_process_callback;
}
function mymodule_field_widget_form_process_callback(array $form, FormStateInterface $form_state) {
// .. do stuff
}
Proposed resolution
Modify the context arrays to pass $form by reference.