2

I have a custom Drupal 8 form using a managed_file field with an #ajax callback but the ajax callback is never called (example below). I assume that it's because the managed file field type is already using ajax. Is there a way that I can implement my own ajax callback within my custom module to fire after the managed file's own ajax completes?

 $form['file'] = array(
      '#title' => t('Image File'),
      '#type' => 'managed_file',
      '#required' => TRUE,
      '#upload_location' => 'private://',
      '#multiple' => FALSE,

      '#upload_validators'    => [
        'file_validate_is_image'      => array(),
        'file_validate_extensions'    => array('jpg png psd ai bmp eps jpeg pdf tif tiff'),
        'file_validate_size'          => array(56600000)
      ],

      '#ajax' => [
        'callback' => array($this, 'myAjaxCallback'),
        'event' => 'change',
        'wrapper' =>  'im-area',
        'progress' => array(
          'type' => 'throbber',
          'message' => t('Choose City'),
        ),
      ],
    );

1 Answer 1

6

I don't think you can attach multiple ajax callbacks to a form element. But you could override the callback by extending the core element:

/src/Element/MyManagedFile.php

<?php

namespace Drupal\mymodule\Element;

use Drupal\file\Element\ManagedFile;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * My Managed File Element.
 *
 * @FormElement("my_managed_file")
 */
class MyManagedFile extends ManagedFile {

 /**
 * {@inheritdoc}
 */
 public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {
    $response = parent::uploadAjaxCallback($form, $form_state, $request);
    $response->addCommand(new AlertCommand('Hello!!!'));
    return $response;
  }

}

And then use it in the custom form:

 $form['file'] = array(
      '#title' => t('Image File'),
      '#type' => 'my_managed_file',
1
  • Great answer. Simply works. Upvoted.
    – salihcenap
    Commented Jul 24, 2021 at 11:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.