Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

CKEditor inline image files usage for custom forms.

By editor , 4 September, 2023
Question

On drupal 10 CKEditor saving inline images as "Temporary" (not saving inline images as "permanent") for custom forms. How to resolve this problem.

Example with CKEditor WYSIWYG inline images field.

Also see : Create a Form with Drupal 8 using Form API

 

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

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

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

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
   $text = $form_state->getValue('text')['value'];
   try {
     self::ckeditorSetFileUsage($text);
   }
   catch (EntityStorageException $e) {
   }
   
   // custom codes.
   
   parent::submitForm($form, $form_state);
}


/**
* Set Images / Filesas Permanent.
*
* @param string $text
*
* @throws \Drupal\Core\Entity\EntityStorageException
*/
 public static function ckeditorSetFileUsage(string $text, $module = 'ckeditor') 
{
   $uuids = _editor_parse_file_uuids($text);
   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, $module, 'file', $file->fid->value);
       }
   }
}

Tags

  • Drupal 10
  • Code
  • Drupal 9
  • Images
Handle file usage with drupal 8
Create a Form with Drupal 8 using Form API

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer