public function YamlFormManagedFileBase::postSave in YAML Form 8
Acts on a saved form submission element before the insert or update hook is invoked.
Parameters
array $element: An element.
\Drupal\yamlform\YamlFormSubmissionInterface $yamlform_submission: A form submission.
bool $update: TRUE if the entity has been updated, or FALSE if it has been inserted.
Overrides YamlFormElementBase::postSave
File
- src/
Plugin/ YamlFormElement/ YamlFormManagedFileBase.php, line 298
Class
- YamlFormManagedFileBase
- Provides a base class form 'managed_file' elements.
Namespace
Drupal\yamlform\Plugin\YamlFormElementCode
public function postSave(array &$element, YamlFormSubmissionInterface $yamlform_submission, $update = TRUE) {
// Get current value and original value for this element.
$key = $element['#yamlform_key'];
$original_data = $yamlform_submission
->getOriginalData();
$data = $yamlform_submission
->getData();
$value = isset($data[$key]) ? $data[$key] : [];
$fids = is_array($value) ? $value : [
$value,
];
$original_value = isset($original_data[$key]) ? $original_data[$key] : [];
$original_fids = is_array($original_value) ? $original_value : [
$original_value,
];
// Check the original submission fids and delete the old file upload.
foreach ($original_fids as $original_fid) {
if (!in_array($original_fid, $fids)) {
file_delete($original_fid);
}
}
// Exit if there is no fids.
if (empty($fids)) {
return;
}
$files = File::loadMultiple($fids);
foreach ($files as $file) {
$source_uri = $file
->getFileUri();
// Replace /_sid_/ token with the submission id.
if (strpos($source_uri, '/_sid_/')) {
$destination_uri = str_replace('/_sid_/', '/' . $yamlform_submission
->id() . '/', $source_uri);
$destination_directory = \Drupal::service('file_system')
->dirname($destination_uri);
file_prepare_directory($destination_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
$destination_uri = file_unmanaged_move($source_uri, $destination_uri);
// Update the file's uri and save.
$file
->setFileUri($destination_uri);
$file
->save();
}
// Update file usage table.
// Set file usage which will also make the file's status permanent.
/** @var \Drupal\file\FileUsage\FileUsageInterface $file_usage */
$file_usage = \Drupal::service('file.usage');
$file_usage
->delete($file, 'yamlform', 'yamlform_submission', $yamlform_submission
->id(), 0);
$file_usage
->add($file, 'yamlform', 'yamlform_submission', $yamlform_submission
->id());
}
}