Converting Drupal 7 ajax_command_replace and render ajax callbacks to Drupal 8

In Drupal 7 a common development pattern to update form elements during an AJAX callback was to use code that did this:

function my_d7_ajax_callback(&$form, &$form_state) {
//Where my_field is a textfield with a div wrapper of my_field_wrapper
$form['my_field']['#value'] = 'new value';
$commands[] = ajax_command_replace('#my_field_wrapper', render($form['my_field']));
return array('#type' => 'ajax', '#commands' => $commands);
}

In Drupal 8 this pattern looks like:

public function my_d8_ajax_callback(array &$form, FormStateInterface $form_state) {
//Where my_field is a textfield with no explicit wrapper.
$form['my_field']['#value'] = "new value";
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('.form-item-my-field', $form['my_field']));
return $response;
}

Important points:

  • D7 ajax_command_replace is ReplaceCommand in D8
  • There is no need to call the render function, D8 automatically renders the specified form item.

Share this post

Leave a comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.

About Us

Congruity Service is a technology solutions company bringing the best technology solutions to OpenInsight projects, Drupal sites, servers, networks, and your technology needs.