0

I have an ajax callback function that needs to return a form element and also an ajax response. Is it possible to do both?

In my callback I need to set and return something like:

$form['fid'] = array(
  '#type' => 'textfield',    
  '#value' => 1,
);
return $form['fid'];

And also something like:

   $response = parent::uploadAjaxCallback($form, $form_state, $request);
   return $response;

Is there a way that I can achieve return both a form element and an ajax response?

EDIT: Latest attempt is returning the form element for display but when I examine the $form from the form build function the value is still empty.

class MyManagedFile extends ManagedFile {

  /**
   * {@inheritdoc}
   */
  public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {


    $response = parent::uploadAjaxCallback($form, $form_state, $request);

    $form['fid'] = array(
      '#type' => 'textfield',
      '#prefix' => '<div id="fid">',
      '#suffix' => '</div>',
      '#value' => '1',
    );

    $response->addCommand(new ReplaceCommand('#fid', $form['fid']));
    return $response;

  }

}

Examining the $form from the form builder (dpm($form)) results in:

[fid] => Array ( [#type] => textfield [#prefix] =>

        [#suffix] => 

    )
0

If you want to do more than simply return new markup, then your response should be an instance of Drupal\Core\Ajax\AjaxResponse, to which you can append one or more AJAX commands via the addCommand() method.

A simplified version of this would be:

use Drupal\Core\Ajax\AjaxResponse;
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#my-wrapper-id', $form['fid']));
return $response;

I recommend checking out a tutorial, such as one of those below, for more information on using AJAX with FAPI:

1
  • Thank you for the reply. I've edited my question with my latest attempt. It is return the form element and populates it for viewing but the #value is not actually set when I examine the $form (dpm($form)) the #value is empty. Any idea how to resolve this? – quantumized Nov 19 '20 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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