Last active
August 24, 2023 20:27
-
-
Save arlina-espinoza/6e0d0f8f84ded0acb2671e272acb835d to your computer and use it in GitHub Desktop.
Drupal 9-10: Save dynamically generated files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\Core\File\FileSystemInterface; | |
use Drupal\Core\Serialization\Yaml; | |
function saveFileDirectly($data) { | |
$encoded = Yaml::encode($data); | |
$filename = 'public://my_dir/my_file.yaml'; | |
// Get the folder for the final location of this style. | |
/** @var \Drupal\Core\File\FileSystemInterface $file_system */ | |
$file_system = \Drupal::service('file_system'); | |
$directory = $file_system->dirname($filename); | |
$file_system->prepareDirectory($directory, FileSyste mInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS); | |
// Save file directly - not invoking hooks or logging in the file_managed table. | |
$path = $file_system->saveData($encoded, $filename, FileSystemInterface::EXISTS_REPLACE); | |
return $path; | |
} | |
function saveFileInManagedFiles($data, NodeInterface $entity) { | |
$encoded = Yaml::encode($data); | |
$filename = 'public://my_dir/my_file.yaml'; | |
/** @var \Drupal\file\FileRepositoryInterface $fileRepository */ | |
$fileRepository = \Drupal::service('file.repository'); | |
$file = $fileRepository->writeData($encoded, $filename, FileSystemInterface::EXISTS_REPLACE); | |
$file->save(); | |
/** @var \Drupal\file\FileUsage\DatabaseFileUsageBackend $file_usage */ | |
$file_usage = \Drupal::service('file.usage'); | |
$file_usage->add($file, 'icims_core', 'node', $entity->id()); | |
return $filename; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment