Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Example: When creating custom config form, sometimes we need to add 'text_format ' field to our form.

Problem: When uploading an image through the CKEditor  in the Advanced HTML/Text editor, the image is not saved as "permanent". The image itself does upload at the time to sites/default/inline-images, however, coming back a day later the image has been deleted.

Solution: Add the snippet below to your custom config form to make sure your images are saved as permanent.

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state)
{

    $form['content'] = [
        '#type' => 'text_format',
        '#format' => 'full_html',
        '#title' => $this->t('Content'),
    ];

    return parent::buildForm($form, $form_state);
}

/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state)
{
    $content = $form_state->getValue('content')['value'];
    $this->custom_editor_record_file_usage($content);
    parent::submitForm($form, $form_state);
}


/**
 * @param $content
 * @throws \Drupal\Core\Entity\EntityStorageException
 */
private function custom_editor_record_file_usage($content)
{
    $uuids = _editor_parse_file_uuids($content);
    foreach ($uuids as $uuid) {
        if ($file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid)) {
            /** @var \Drupal\file\FileInterface $file */
            if ($file->isTemporary()) {
                $file->setPermanent();
                $file->save();
            }
            \Drupal::service('file.usage')->add($file, 'editor', 'file', $file->fid->value);
        }
    }
}

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal, Laravel.

Web Posts

Search

Page Facebook