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);
        }
    }
}

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon