0

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, \Drupal\Core\Form\FormStateInterface $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

0

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().

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.