Question

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'),
        ),
      ],
    );
Was it helpful?

Solution

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',
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top