public static function ManagedFile::uploadAjaxCallback in Drupal 8
Same name and namespace in other branches
- 9 core/modules/file/src/Element/ManagedFile.php \Drupal\file\Element\ManagedFile::uploadAjaxCallback()
#ajax callback for managed_file upload forms.
This ajax callback takes care of the following things:
- Ensures that broken requests due to too big files are caught.
- Adds a class to the response to be able to highlight in the UI, that a new file got uploaded.
Parameters
array $form: The build form.
\Drupal\Core\Form\FormStateInterface $form_state: The form state.
\Symfony\Component\HttpFoundation\Request $request: The current request.
Return value
\Drupal\Core\Ajax\AjaxResponse The ajax response of the ajax upload.
File
- core/
modules/ file/ src/ Element/ ManagedFile.php, line 178
Class
- ManagedFile
- Provides an AJAX/progress aware widget for uploading and saving a file.
Namespace
Drupal\file\ElementCode
public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
$form_parents = explode('/', $request->query
->get('element_parents'));
// Sanitize form parents before using them.
$form_parents = array_filter($form_parents, [
Element::class,
'child',
]);
// Retrieve the element to be rendered.
$form = NestedArray::getValue($form, $form_parents);
// Add the special AJAX class if a new file was added.
$current_file_count = $form_state
->get('file_upload_delta_initial');
if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
$form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
}
else {
$form['#suffix'] .= '<span class="ajax-new-content"></span>';
}
$status_messages = [
'#type' => 'status_messages',
];
$form['#prefix'] .= $renderer
->renderRoot($status_messages);
$output = $renderer
->renderRoot($form);
$response = new AjaxResponse();
$response
->setAttachments($form['#attached']);
return $response
->addCommand(new ReplaceCommand(NULL, $output));
}