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!

Related Questions

” a field on Manage display

1  Asked on February 6, 2021 by carrotandme


Display Entity Reference field twice, with different display modes

1  Asked on February 3, 2021 by paul-canning


Media html not rendering in blocks

1  Asked on February 3, 2021 by kristoffer-rom


How can I programmatically change the view mode?

4  Asked on February 3, 2021 by jmzea


How do I avoid API calls are cached?

2  Asked on February 2, 2021 by user1648228


Custom JSON api normalizer is not initiated

0  Asked on February 1, 2021 by kevinvhengst


Suddenly unable to add a field to a new content type

1  Asked on January 31, 2021 by leif


an error when changing the date form

1  Asked on January 30, 2021 by mahdi-alikhasi


Display content based on taxonomy with view

2  Asked on January 30, 2021


Why is my code called again written on build form?

0  Asked on January 29, 2021 by namit-garg


How to change path of taxonomy facet

1  Asked on January 24, 2021 by rahulkumar-it


Form field not show on Ajax Callback even the callback is called

1  Asked on January 23, 2021 by emad-karhely


Features to import content types

2  Asked on January 18, 2021 by webmaster-pf


Redirect user to previous page after registration

2  Asked on January 15, 2021 by lbogdan


field_info_field: how to define the content type name?

1  Asked on January 14, 2021 by bruno-von-paris


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP