php - How to programmatically add images by their fid to the node creationediting form in Drupal 8 when a button is pressed? - S

admin2025-04-25  2

I am developing a custom solution in Drupal 8 where I need to programmatically add images (by their fid) to the image field in the node creation/editing form.

Currently:

  • I have overridden the ImageWidget plugin and use the formMultipleElements method to add images to the field.

  • This works when the page is reloaded or when a new image is uploaded using the default functionality.

However, I need the images to be added to the field when an AJAX button is pressed, without reloading the page.

What I have tried:

  1. Added an AJAX button to the form.

  2. In the button's callback, I try to update the image field by returning the modified element from formMultipleElements.

  3. Tried saving data using $form_state and updating the field's value with #default_value.

The Problem:

When I press the button, the image field disappears or does not update as expected.
The images I add via formMultipleElements only appear after the page is reloaded or when a new image is uploaded through the UI.

What I want:

  • When the button is pressed, images (with specific fids) should be added to the image field.

  • The images should immediately appear in the form (e.g., with their preview).

  • The field should correctly save these images when the node form is submitted.

Code:

Here’s a part of my code where I add images:

$elements = parent::formMultipleElements($items, $form, $form_state);
if (!$form_state->isRebuilding()) {
  $uniq_id = '675d4801b3b4a';
}
$query = \Drupal::database()->select('tmp_image', 'ti')->fields('ti', ['fid']);
$res = $query->condition('uuid', $uniq_id)
  ->execute()
  ->fetchCol('fid'); // Add files to the field.
$inputElem = $elements[$elements['#file_upload_delta']];
foreach ($res as $file_id) {
  $newElem = $inputElem;
  $newElem['#default_value'] = [
    'target_id' => $file_id,
    'alt' => '',
    'title' => '',
    'width' => 768,
    'height' => 1024,
  ];
  $elements[$elements['#file_upload_delta'] + 1] = $newElem;
  $elements['#file_upload_delta']++;
}
return $elements;

How can I properly update the image field via AJAX so that it shows the added images without reloading the page and saves them when the form is submitted??

转载请注明原文地址:http://anycun.com/QandA/1745595394a90943.html