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.
Leave a comment