setFilterConfig example

public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form$form_state);

    // Add the submitted form values to the text format, and save it.     $format = $this->entity;
    foreach ($form_state->getValues() as $key => $value) {
      if ($key != 'filters') {
        $format->set($key$value);
      }
      else {
        foreach ($value as $instance_id => $config) {
          $format->setFilterConfig($instance_id$config);
        }
      }
    }
    $format->save();

    // Save user permissions.     if ($permission = $format->getPermissionName()) {
      foreach ($form_state->getValue('roles') as $rid => $enabled) {
        user_role_change_permissions($rid[$permission => $enabled]);
      }
    }

    
'toolbar' => [
          'items' => [],
        ],
        'plugins' => [
          'media_media' => [
            'allow_view_mode_override' => TRUE,
          ],
        ],
      ],
    ]);
    $this->editor->save();
    $filtered_html_format->setFilterConfig('media_embed', [
      'status' => TRUE,
      'settings' => [
        'default_view_mode' => 'view_mode_1',
        'allowed_media_types' => [],
        'allowed_view_modes' => [
          'view_mode_1' => 'view_mode_1',
          'view_mode_2' => 'view_mode_2',
        ],
      ],
    ])->save();

    

    $this->assertEditorButtonEnabled('Undo');
    $this->pressEditorButton('Undo');
    $this->assertEmpty($assert_session->waitForElementVisible('css', $media_preview_selector, 1000));
    $this->assertEditorButtonDisabled('Undo');
    $this->pressEditorButton('Redo');
    $this->assertEditorButtonEnabled('Undo');

    // Ensure that data-align attribute is set by default when media is inserted     // while filter_align is enabled.     FilterFormat::load('test_format')
      ->setFilterConfig('filter_align', ['status' => TRUE])
      ->save();
    $this->drupalGet('/node/add/blog');
    $this->waitForEditor();
    $this->pressEditorButton('Insert Media');
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '#drupal-modal #media-library-content'));
    $assert_session->elementExists('css', '.js-media-library-item')->click();
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Insert selected');
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', $media_preview_selector, 1000));
    $xpath = new \DOMXPath($this->getEditorDataAsDom());
    $drupal_media = $xpath->query('//drupal-media')[0];
    $expected_attributes = [
      
$settings = $text_editor->getSettings();
      $settings['plugins']['ckeditor5_sourceEditing']['allowed_tags'][] = $allowed_elements_string;
      $text_editor->setSettings($settings);

      // Keep the allowed HTML tags in sync.       $text_format = FilterFormat::load('test_format');
      $allowed_elements = HTMLRestrictions::fromTextFormat($text_format);
      $updated_allowed_tags = $allowed_elements->merge(HTMLRestrictions::fromString($allowed_elements_string));
      $filter_html_config = $text_format->filters('filter_html')
        ->getConfiguration();
      $filter_html_config['settings']['allowed_html'] = $updated_allowed_tags->toFilterHtmlAllowedTagsString();
      $text_format->setFilterConfig('filter_html', $filter_html_config);

      // Verify the text format and editor are still a valid pair.       $this->assertSame([]array_map(
        function DConstraintViolation $v) {
          return (string) $v->getMessage();
        },
        iterator_to_array(CKEditor5::validatePair(
          $text_editor,
          $text_format
        ))
      ));

      
$plugin_ids = array_keys($this->manager->getEnabledDefinitions($editor));
    $default_plugins_with_layercake = array_merge($default_plugins['ckeditor5_test_layercake']);

    // Sort on plugin id.     asort($default_plugins_with_layercake);
    $this->assertSame(array_values($default_plugins_with_layercake)$plugin_ids);
    $default_libraries_with_layercake = array_merge($default_libraries['ckeditor5_test/layercake']);
    sort($default_libraries_with_layercake);
    $this->assertSame($default_libraries_with_layercake$this->manager->getEnabledLibraries($editor));

    // Enable media embed filter which the CKEditor 5 media plugin requires.     $editor->getFilterFormat()->setFilterConfig('media_embed', ['status' => TRUE])->save();

    // Case 4: The CKEditor 5 media plugin should be enabled and the library     // should be available now that the media_embed is enabled.     $plugin_ids = array_keys($this->manager->getEnabledDefinitions($editor));
    $expected_plugins = array_merge($default_plugins[
      'ckeditor5_drupalMediaCaption',
      'ckeditor5_test_layercake',
      'media_media',
      'media_mediaAlign',
    ]);
    sort($expected_plugins);
    
public function testDisabledFormat() {
    // Create a node type and add a standard body field.     $node_type = NodeType::create(['type' => mb_strtolower($this->randomMachineName())]);
    $node_type->save();
    node_add_body_field($node_type$this->randomString());

    // Create a text format with a filter that returns a static string.     $format = FilterFormat::create([
      'name' => $this->randomString(),
      'format' => $format_id = mb_strtolower($this->randomMachineName()),
    ]);
    $format->setFilterConfig('filter_static_text', ['status' => TRUE]);
    $format->save();

    // Create a new node of the new node type.     $node = Node::create([
      'type' => $node_type->id(),
      'title' => $this->randomString(),
    ]);
    $body_value = $this->randomString();
    $node->body->value = $body_value;
    $node->body->format = $format_id;
    $node->save();

    
'enabled' => TRUE,
      'label' => 'View Mode 1',
    ])->setSyncing(TRUE)->save();
    EntityViewMode::create([
      'id' => 'media.view_mode_2',
      'targetEntityType' => 'media',
      'status' => TRUE,
      'enabled' => TRUE,
      'label' => 'View Mode 2',
    ])->setSyncing(TRUE)->save();
    $filter_format = FilterFormat::load('basic_html_with_media_embed_view_mode_enabled_two_view_modes_configured');
    $filter_format->setFilterConfig('media_embed', [
      'status' => TRUE,
      'settings' => [
        'default_view_mode' => 'view_mode_1',
        'allowed_media_types' => [],
        'allowed_view_modes' => [
          'view_mode_1' => 'view_mode_1',
          'view_mode_2' => 'view_mode_2',
        ],
      ],
    ])->setSyncing(TRUE)->save();

    
'format' => 'empty_format',
      'name' => 'Empty format',
    ]);
    $format->save();
    $this->verifyTextFormat($format);

    // Add another text format specifying all possible properties.     $format = FilterFormat::create([
      'format' => 'custom_format',
      'name' => 'Custom format',
    ]);
    $format->setFilterConfig('filter_url', [
      'status' => 1,
      'settings' => [
        'filter_url_length' => 30,
      ],
    ]);
    $format->save();
    $this->verifyTextFormat($format);

    // Alter some text format properties and save again.     $format->set('name', 'Altered format');
    $format->setFilterConfig('filter_url', [
      


  /** * Tests that `uploadImage` toolbar item is updated to `drupalInsertImage`. * * @dataProvider provider */
  public function test(bool $filter_html_is_enabled, bool $image_uploads_are_enabled, bool $source_editing_is_already_enabled, array $expected_source_editing_additions): void {
    // Apply tweaks for the currently provided test case.     $format = FilterFormat::load('test_format_image');
    if (!$filter_html_is_enabled) {
      $format->setFilterConfig('filter_html', ['status' => FALSE]);
    }
    $editor = Editor::load('test_format_image');
    if (!$image_uploads_are_enabled) {
      $editor->setImageUploadSettings(['status' => FALSE]);
    }
    if (!$source_editing_is_already_enabled) {
      $settings = $editor->getSettings();
      // Remove the `sourceEditing` toolbar item.       unset($settings['toolbar']['items'][3]);
      // Remove the corresponding plugin settings (allowing `<img data-foo>`).       unset($settings['plugins']['ckeditor5_sourceEditing']);
      
$editor = Editor::load('test_format');
    $settings = $editor->getSettings();

    // Allow the data-foo attribute in drupal-media via GHS. Also, add support     // for div's with data-foo attribute to ensure that drupal-media elements     // can be wrapped with other block elements.     $settings['plugins']['ckeditor5_sourceEditing']['allowed_tags'] = ['<drupal-media data-foo>', '<div data-bar>'];
    $editor->setSettings($settings);
    $editor->save();

    $filter_format = $editor->getFilterFormat();
    $filter_format->setFilterConfig('filter_html', [
      'status' => TRUE,
      'settings' => [
        'allowed_html' => '<p> <br> <strong> <em> <a href> <drupal-media data-entity-type data-entity-uuid data-align data-caption alt data-foo data-view-mode> <div data-bar>',
      ],
    ]);
    $filter_format->save();
    $this->assertSame([]array_map(
      function DConstraintViolation $v) {
        return (string) $v->getMessage();
      },
      iterator_to_array(CKEditor5::validatePair(
        

      ],
    ]);
    $crazy_format->save();
    // Use config to directly load the configuration and check that only enabled     // or customized plugins are saved to configuration.     $filters = $this->config('filter.format.crazy')->get('filters');
    $this->assertEquals(['filter_html_escape', 'filter_html']array_keys($filters));

    // Disable a plugin to ensure that disabled plugins with custom settings are     // stored in configuration.     $crazy_format->setFilterConfig('filter_html_escape', ['status' => FALSE]);
    $crazy_format->save();
    $filters = $this->config('filter.format.crazy')->get('filters');
    $this->assertEquals(['filter_html_escape', 'filter_html']array_keys($filters));

    // Set the settings as per default to ensure that disable plugins in this     // state are not stored in configuration.     $crazy_format->setFilterConfig('filter_html_escape', ['weight' => -10]);
    $crazy_format->save();
    $filters = $this->config('filter.format.crazy')->get('filters');
    $this->assertEquals(['filter_html']array_keys($filters));
  }

  
    // @see \Drupal\filter\FilterFormatFormBase::submitForm()     $filter_format_form_values = array_intersect_key(
      $filter_format_form_state->getValues(),
      array_flip(['filters', 'filter_settings']
    ));
    foreach ($filter_format_form_values as $key => $value) {
      if ($key !== 'filters') {
        $submitted_filter_format->set($key$value);
      }
      else {
        foreach ($value as $instance_id => $config) {
          $submitted_filter_format->setFilterConfig($instance_id$config);
        }
      }
    }

    return $submitted_filter_format;
  }

  /** * Gets the eventual text format config entity: from form state + editor. * * Needed for validation. * * @param \Drupal\Core\Form\SubformStateInterface $editor_form_state * The text editor configuration form's form state. * @param \Drupal\editor\EditorInterface $submitted_editor * The current text editor config entity. * * @return \Drupal\editor\EditorInterface * A clone of the received Editor config entity , with a primed associated * FilterFormat that corresponds to the current form state, to avoid the * stored FilterFormat config entity being loaded. */
$editor = Editor::load('test_format');
    $settings = $editor->getSettings();

    // Allow the data-foo attribute in img via GHS.     $settings['plugins']['ckeditor5_sourceEditing']['allowed_tags'] = ['<img data-foo>'];
    $editor->setSettings($settings);
    $editor->save();

    // Disable filter_html.     if ($unrestricted) {
      FilterFormat::load('test_format')
        ->setFilterConfig('filter_html', ['status' => FALSE])
        ->save();
    }

    // Make the test content have either a block image or an inline image.     $img_tag = '<img data-foo="bar" alt="drupalimage test image" data-entity-type="file" ' . $this->imageAttributesAsString() . ' />';
    $this->host->body->value .= $image_type === 'block'
      ? $img_tag
      : "<p>$img_tag</p>";
    $this->host->save();

    $expected_widget_selector = $image_type === 'block' ? 'image img' : 'image-inline';

    
$has_html_restrictions = $editor->getFilterFormat()->filters('filter_html')->status;
    $missing_fundamental_tags = HTMLRestrictions::emptySet();
    if ($has_html_restrictions) {
      $fundamental = new HTMLRestrictions($this->pluginManager->getProvidedElements([
        'ckeditor5_essentials',
        'ckeditor5_paragraph',
      ]));
      $filter_html_restrictions = HTMLRestrictions::fromTextFormat($editor->getFilterFormat());
      $missing_fundamental_tags = $fundamental->diff($filter_html_restrictions);
      if (!$missing_fundamental_tags->allowsNothing()) {
        $editor->getFilterFormat()->setFilterConfig('filter_html', $filter_html_restrictions->merge($fundamental)->getAllowedElements());
        $this->logger->warning("As part of migrating the %text_format text format to CKEditor 5, the following tag(s) were added to <em>Limit allowed HTML tags and correct faulty HTML</em>, because they are needed to provide fundamental CKEditor 5 functionality : @missing_tags. The text format must be saved to make these changes active.", [
          '%text_format' => $editor->getFilterFormat()->get('name'),
          '@missing_tags' => $missing_fundamental_tags->toFilterHtmlAllowedTagsString(),
        ]);
      }
    }

    // Finally: for all enabled plugins, find the ones that are configurable,     // and add their default settings. For enabled plugins with element subsets,     // compute the appropriate settings to achieve the subset that matches the     // original text format restrictions.
Home | Imprint | This part of the site doesn't use cookies.