TransWikia.com

How can I rebuild an image field with values in an Ajax callback?

Drupal Answers Asked by Wassim Akermi on December 17, 2020

in Drupal 8 I have media form with select box having ajax property and an image field.
on select box value change I want to assign specific file to the image field.
On form_alter this code work, the image field received the file and correctly rendered.

$form['field_media_image']['widget'][0]['#default_value'] = array('target_id' => "165", 'alt' => 'ttt', 'fids' => ["165"]);

but on ajax callback it’s not working even if I set value.

function myAjaxCallback(array &$form, DrupalCoreFormFormStateInterface $form_state) {
  $form['field_media_image']['widget'][0]['target_id']['value'] = array('target_id' => 165, 'alt' => 'ttt', 'fids' => [165]);
  return $form['field_media_image'];
}

Thanks for helping

One Answer

You cannot alter the form in the Ajax callback. Instead, you must put a check in your form if an Ajax action is triggered and if so, set the default value.

I did this once in D7 and managed to get it to work by doing the following:

  1. Give the Ajax button a name attribute.
  2. Somewhere in the form, check if $form_state['input']['_triggering_element_name'] is set and when it matches the name of the Ajax button, alter the $form.

In D8, I think you can get the clicked button with $form_state->getTriggeringElement().

Answered by Patrick Scheffer on December 17, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP