function ManagedFile::uploadAjaxCallback

Same name in other branches
  1. 8.9.x core/modules/file/src/Element/ManagedFile.php \Drupal\file\Element\ManagedFile::uploadAjaxCallback()
  2. 10 core/modules/file/src/Element/ManagedFile.php \Drupal\file\Element\ManagedFile::uploadAjaxCallback()
  3. 11.x 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 180

Class

ManagedFile
Provides an AJAX/progress aware widget for uploading and saving a file.

Namespace

Drupal\file\Element

Code

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';
    }
    $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));
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.