I am using Drupal 9.3 and Webform 6.1.7.
I have a Webform that contains a file element and am building a custom form to update the submission data.
I have found that when I submit my custom form I can load the Webform submission and set the file IDs and it will save the data fine with no issues.
However when it comes to removing a file after saving, the file I remove just remains attached.
I know that using the Webform interface the file upload / remove is working fine. However it seems to be a problem with removing files when updating the submission programmatically.
Is there any extra step I am missing to remove the files?
This is really simple version of the form I am building:
<?php
namespace Drupal\example\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides an example form.
*/
class WebformFileUpdateForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'example_webform_file_update_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$em = \Drupal::entityTypeManager();
// Load all webform submissions for the node.
$nid = 86552;
$query = $em->getStorage('webform_submission')
->getQuery()
->condition('webform_id', 'tutorial', '=')
->condition('entity_id', $nid)
->pager(10);
$submission_ids = $query->execute();
$webform_submissions = $em->getStorage('webform_submission')
->loadMultiple($submission_ids);
$form['#tree'] = TRUE;
$form['files'] = [
'#type' => 'fieldset',
'#title' => $this->t('Files'),
];
foreach ($webform_submissions as $submission) {
$form['files'][$submission->id()]['file'] = [
'#type' => 'managed_file',
'#title' => $this->t('File'),
'#default_value' => $submission->getElementData('attached_files'),
'#upload_location' => 'private://tutorials/' . $submission->id() . '/',
'#multiple' => TRUE,
];
}
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Update'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$em = \Drupal::entityTypeManager();
$values = $form_state->getValues();
foreach ($values['files'] as $sid => $data) {
$em->getStorage('webform_submission')
->load($sid)
->setElementData('attached_files', $data['file'])
->save();
}
}
}