Problem when putting space on the name of the anchor

Created on 15 November 2017, about 7 years ago
Updated 29 February 2024, 10 months ago

Hi,

When I try to create an anchor containing a space. The link will not work properly.
Il will share a new patch.

Thx
Akram AMOURI

🐛 Bug report
Status

Closed: won't fix

Version

1.6

Component

Code

Created by

🇫🇷France aamouri

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇧🇪Belgium fernly

    For people encountering this problem: This can also be fixed without the patch and instead add a custom text format filter in your custom module.

    my_module/src/Plugin/Filter/AnchorFilter.php

    namespace Drupal\my_module\Plugin\Filter;
    
    use Drupal\Component\Utility\Html;
    use Drupal\filter\FilterProcessResult;
    use Drupal\filter\Plugin\FilterBase;
    
    /**
     * Custom text format filter to fix anchor id's with spaces.
     *
     * This will:
     * - Replace spaces in anchor link ID's by hyphens (-).
     * - Add unique postfix when link IDs are duplicated on a page.
     *
     * @Filter(
     *   id = "filter_anchor",
     *   title = @Translation("Anchor Filter"),
     *   description = @Translation("Help this text format fix id's with spaces between"),
     *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE,
     * )
     */
    final class AnchorFilter extends FilterBase {
    
      /**
       * Creates unique ids for each anchor link.
       */
      public function process($text, $langcode): FilterProcessResult {
        $dom = Html::load($text);
    
        $links = $dom->getElementsByTagName('a');
        /** @var \DOMElement $link */
        foreach ($links as $link) {
          $this->cleanLinkId($link);
        }
    
        return new FilterProcessResult(Html::serialize($dom));
      }
    
      /**
       * Cleanup given link DOM Element.
       *
       * This will clean the ID only when:
       * - Link is not a normal link (with href).
       * - Link has ID.
       * - Unique ID will be generated from link ID.
       *
       * @param \DOMElement $link
       *   The link element.
       */
      private function cleanLinkId(\DOMElement $link): void {
        if (!empty($link->getAttribute('href'))) {
          return;
        }
    
        $linkId = $link->getAttribute('id');
        if (!$linkId) {
          return;
        }
    
        $link->setAttribute(
          'id',
          Html::getUniqueId($linkId)
        );
      }
    
    }
    

    Enable this filter in your respective text formats.

Production build 0.71.5 2024