public function AddMediaFormBase::updateFormCallback in Media Directories 3.x
Same name and namespace in other branches
- 8 modules/media_directories_ui/src/Form/AddMediaFormBase.php \Drupal\media_directories_ui\Form\AddMediaFormBase::updateFormCallback()
- 2.x modules/media_directories_ui/src/Form/AddMediaFormBase.php \Drupal\media_directories_ui\Form\AddMediaFormBase::updateFormCallback()
AJAX callback to update the entire form based on source field input.
Parameters
array $form: The complete form.
\Drupal\Core\Form\FormStateInterface $form_state: The current form state.
Return value
\Drupal\Core\Ajax\AjaxResponse|array The form render array or an AJAX response object.
Overrides AddFormBase::updateFormCallback
File
- modules/
media_directories_ui/ src/ Form/ AddMediaFormBase.php, line 96
Class
- AddMediaFormBase
- Class AddMediaFormBase
Namespace
Drupal\media_directories_ui\FormCode
public function updateFormCallback(array &$form, FormStateInterface $form_state) {
$triggering_element = $form_state
->getTriggeringElement();
$wrapper_id = $triggering_element['#ajax']['wrapper'];
$added_media = $form_state
->get('media');
$response = new AjaxResponse();
// When the source field input contains errors, replace the existing form to
// let the user change the source field input. If the user input is valid,
// the entire modal is replaced with the second step of the form to show the
// form fields for each media item.
if ($form_state::hasAnyErrors()) {
$response
->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $form));
return $response;
}
// Check if the remove button is clicked.
if (end($triggering_element['#parents']) === 'remove_button') {
// When the list of added media is empty, return to the media library and
// shift focus back to the first tabbable element (which should be the
// source field).
if (empty($added_media)) {
$form_state
->setRebuild();
$response
->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $this
->buildMediaLibraryUi($form_state)));
$response
->addCommand(new InvokeCommand('#media-library-add-form-wrapper :tabbable', 'focus'));
}
else {
$response
->addCommand(new ReplaceCommand("#{$wrapper_id}", $form));
// Find the delta of the next media item. If there is no item with a
// bigger delta, we automatically use the delta of the previous item and
// shift the focus there.
$removed_delta = array_slice($triggering_element['#array_parents'], -2, 1)[0];
$delta_to_focus = 0;
foreach ($added_media as $delta => $media) {
$delta_to_focus = $delta;
if ($delta > $removed_delta) {
break;
}
}
$response
->addCommand(new InvokeCommand(".media-library-add-form__media[data-media-library-added-delta={$delta_to_focus}]", 'focus'));
}
}
else {
$response
->addCommand(new ReplaceCommand("#{$wrapper_id}", $form));
$response
->addCommand(new InvokeCommand('.media-library-add-form__added-media', 'focus'));
}
return $response;
}