How to fix inline images deleted after cron

By admin, 28 十一月, 2019

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

标签

评论

Restricted HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <img src>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。
验证码
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
请输入"Drupal10"

最新评论