When we build a form with text_format field in Drupal 8, images inserted in ckeditor is temporary and will be deleted 6 hours after cron by default.
$form['content'] = [
'#type' => 'text_format',
'#title' => 'Content',
'#format' => 'full_html',
'#expected_value' => [
'value' => 'Text value',
'format' => 'plain_text',
],
];
To fix this issue, I write a patch and execute that patch at the end of form submit.
TextFormatPatch::addFileUsage($content, 'your_module', 'your_type', $id);
Here is the content of the patch:
<?php
namespace Drupal\utility\Image;
use Drupal\file\Entity\File;
/**
* Patch of fixing inline images deleted after cron.
*
* Issue: https://www.drupal.org/project/drupal/issues/2857444
*/
class TextFormatPatch {/**
* Add file usage for inline images.
*/
public static function addFileUsage($html, $module, $type, $id) {
$files = TextFormatPatch::findInlineImages($html);
foreach ($files as $file) {
\Drupal::service('file.usage')
->add($file, $module, $type, $id);
}
}/**
* Delete file usage after image removed.
*/
public static function delFileUsage($oldHtml, $newHtml) {}
/**
* Return inline image files in text_format field content.
*/
private static function findInlineImages($html) {
$count = preg_match_all('/data-entity-uuid="([^"]+)"/', $html, $matches,
PREG_PATTERN_ORDER);$files = [];
if ($count) {
for ($i = 0; $i < $count; $i++) {
$uuid = $matches[1][$i];
$fid = TextFormatPatch::getFidByUuid($uuid);
if ($fid) {
$files[] = File::load($fid);
}
}
}return $files;
}/**
* Get file fid by uuid.
*/
private static function getFidByUuid($uuid) {
$row = \Drupal::database()->select('file_managed', 'f')
->fields('f', ['fid'])
->condition('uuid', $uuid)
->execute()
->fetch();if ($row) {
return $row->fid;
}return FALSE;
}}
相关issue:https://www.drupal.org/project/drupal/issues/2857444
评论