TYPO3 Logo
TYPO3 Explained
Release: 11.5

Loading data.

  • Introduction
  • API A-Z
    • Assets (CSS, JavaScript, Media)
    • Authentication
      • Multi-Factor Authentication
    • Autoloading
      • ComposerClassLoader
    • Backend APIs
      • Access control in the backend (users and groups)
        • Users and groups
        • Password reset functionality
        • Roles
        • Access Control Options
        • Other Options
        • More about file mounts
        • Backend users module
      • Ajax in the Backend
      • Ajax in the backend, client-side
      • Backend layout
      • Backend routing
      • Backend user object
      • Broadcast channels
      • Clipboard
      • Context-sensitive menus
      • Using Custom Permission Options
      • Links to Edit Records
      • Backend login form API
    • Caching
      • Quick Start for Integrators
      • Configuration
      • Caching Framework Architecture
      • Cache frontends
      • Cache backends
      • Developer Information
    • System categories
    • Console commands (cli)
      • Tutorial
    • Content Elements & Plugins
      • Introduction
      • Create a custom content element type
      • Custom data processors
      • Create plugins
      • Configure custom backend preview for content element
      • Add content elements to the Content Element Wizard
      • Best practices
    • Context API and Aspects
    • Context Sensitive Help (CSH)
      • The $TCA_DESCR Array
      • The Language Files for CSH
      • Implementing CSH
    • Crop Variants for Images
      • General Configuration
      • Crop variants configuration per content element
    • Data Formats
      • T3DataStructure
        • Elements
        • Sheet References
        • Parsing a Data Structure
    • Database (Doctrine DBAL)
      • Introduction
      • Configuration
      • Database structure
      • Upgrade table and field definitions
      • Basic create, read, update, and delete operations (CRUD)
      • Class overview
      • ConnectionPool
      • Query builder
      • Connection
      • Expression builder
      • Restriction builder
      • Result
      • Migrating from TYPO3_DB
      • Various tips and tricks
    • Debugging
    • Dependency injection
    • Deprecation
    • Directory structure
      • Legacy installations: Directory structure
    • Enumerations & BitSets
      • How to use enumerations
      • How to use bitsets
    • Environment
    • Error and exception handling
      • Configuration
      • Error Handler
      • Production Exception Handler
      • Debug exception handler
      • Examples
      • How to extend the error and exception handling
    • Events, signals and hooks
      • Extending the TYPO3 Core
      • EventDispatcher (PSR-14 Events)
      • Event list
        • Backend
          • AfterFormEnginePageInitializedEvent
          • AfterHistoryRollbackFinishedEvent
          • AfterPageColumnsSelectedForLocalizationEvent
          • BeforeFormEnginePageInitializedEvent
          • BeforeHistoryRollbackStartEvent
          • ModifyClearCacheActionsEvent
          • ModifyPageLayoutOnLoginProviderSelectionEvent
          • SwitchUserEvent
          • SystemInformationToolbarCollectorEvent
        • Core
          • Authentication
            • AfterGroupsResolvedEvent
          • Configuration
            • AfterTcaCompilationEvent
            • ModifyLoadedPageTsConfigEvent
          • Core
            • BootCompletedEvent
          • DataHandling
            • AppendLinkHandlerElementsEvent
            • IsTableExcludedFromReferenceIndexEvent
          • Database
            • AlterTableDefinitionStatementsEvent
          • Html
            • BrokenLinkAnalysisEvent
          • Mail
            • AfterMailerInitializationEvent
          • Package
            • AfterPackageActivationEvent
            • AfterPackageDeactivationEvent
            • BeforePackageActivationEvent
            • PackagesMayHaveChangedEvent
          • Page
            • BeforeJavaScriptsRenderingEvent
            • BeforeStylesheetsRenderingEvent
          • Resource
            • AfterFileAddedEvent
            • AfterFileAddedToIndexEvent
            • AfterFileCommandProcessedEvent
            • AfterFileContentsSetEvent
            • AfterFileCopiedEvent
            • AfterFileCreatedEvent
            • AfterFileDeletedEvent
            • AfterFileMarkedAsMissingEvent
            • AfterFileMetaDataCreatedEvent
            • AfterFileMetaDataDeletedEvent
            • AfterFileMetaDataUpdatedEvent
            • AfterFileMovedEvent
            • AfterFileProcessingEvent
            • AfterFileRemovedFromIndexEvent
            • AfterFileRenamedEvent
            • AfterFileReplacedEvent
            • AfterFileUpdatedInIndexEvent
            • AfterFolderAddedEvent
            • AfterFolderCopiedEvent
            • AfterFolderDeletedEvent
            • AfterFolderMovedEvent
            • AfterFolderRenamedEvent
            • AfterResourceStorageInitializationEvent
            • BeforeFileAddedEvent
            • BeforeFileContentsSetEvent
            • BeforeFileCopiedEvent
            • BeforeFileCreatedEvent
            • BeforeFileDeletedEvent
            • BeforeFileMovedEvent
            • BeforeFileProcessingEvent
            • BeforeFileRenamedEvent
            • BeforeFileReplacedEvent
            • BeforeFolderAddedEvent
            • BeforeFolderCopiedEvent
            • BeforeFolderDeletedEvent
            • BeforeFolderMovedEvent
            • BeforeFolderRenamedEvent
            • BeforeResourceStorageInitializationEvent
            • EnrichFileMetaDataEvent
            • GeneratePublicUrlForResourceEvent
            • ModifyFileDumpEvent
            • ModifyIconForResourcePropertiesEvent
            • SanitizeFileNameEvent
          • Tree
            • ModifyTreeDataEvent
        • Extbase
          • Mvc
            • AfterRequestDispatchedEvent
            • BeforeActionCallEvent
          • Persistence
            • AfterObjectThawedEvent
            • EntityAddedToPersistenceEvent
            • EntityPersistedEvent
            • EntityRemovedFromPersistenceEvent
            • EntityUpdatedInPersistenceEvent
            • ModifyQueryBeforeFetchingObjectDataEvent
            • ModifyResultAfterFetchingObjectDataEvent
        • ExtensionManager
          • AfterExtensionDatabaseContentHasBeenImportedEvent
          • AfterExtensionFilesHaveBeenImportedEvent
          • AfterExtensionStaticDatabaseContentHasBeenImportedEvent
          • AvailableActionsForExtensionEvent
        • Filelist
          • ProcessFileListActionsEvent
        • Frontend
          • ModifyHrefLangTagsEvent
          • ModifyResolvedFrontendGroupsEvent
        • FrontendLogin
          • BeforeRedirectEvent
          • LoginConfirmedEvent
          • LoginErrorOccurredEvent
          • LogoutConfirmedEvent
          • ModifyLoginFormViewEvent
          • PasswordChangeEvent
          • SendRecoveryEmailEvent
        • Impexp
          • BeforeImportEvent
        • Install
          • ModifyLanguagePackRemoteBaseUrlEvent
        • Linkvalidator
          • BeforeRecordIsAnalyzedEvent
        • Recordlist
          • ModifyRecordListHeaderColumnsEvent
          • ModifyRecordListRecordActionsEvent
          • ModifyRecordListTableActionsEvent
          • RenderAdditionalContentToRecordListEvent
        • Seo
          • ModifyUrlForCanonicalTagEvent
        • Setup
          • AddJavaScriptModulesEvent
        • Workspaces
          • AfterCompiledCacheableDataForWorkspaceEvent
          • AfterDataGeneratedForWorkspaceEvent
          • GetVersionedDataEvent
          • SortVersionedDataEvent
      • Signals and slots (deprecated)
      • Hooks
      • JavaScript Event API
        • Regular event
        • Debounce event
        • Throttle event
        • RequestAnimationFrame event
    • File abstraction layer (FAL)
      • Introduction
      • Basic concepts
      • Architecture
        • Overview
        • Folders
        • Database structure
        • Components
        • PSR-14 Events
      • Administration
        • Permissions
        • File storages
        • Maintenance
      • Using FAL
        • Using FAL in the Frontend
        • TCA Definition
        • The StorageRepository Class
        • Working With files, folders and file references
        • Working With Collections
        • Searching for Files
      • File collections
    • Custom file processors
    • Flash messages
    • FlexForms
    • Fluid
      • Introduction to Fluid
      • Fluid syntax
      • Using Fluid in TYPO3
      • cObject ViewHelper
      • Property additionalAttributes
      • Developing a custom ViewHelper
      • ViewHelper reference
    • FormEngine
      • Introduction
      • Main rendering workflow
      • Data compiling
      • Rendering
    • Form protection tool
    • Global values
      • Constants
    • Icon API
    • JavaScript in TYPO3 Backend
      • RequireJS in the TYPO3 Backend
        • Use RequireJS in your own extension
        • Dependency handling
        • Loading your own or other RequireJS modules
        • Shim Library to Use it as Own RequireJS Modules
      • Client-side templating
      • Various JavaScript modules
        • Modals
        • Multi-step wizard
        • DocumentService (jQuery.ready substitute)
        • SessionStorage wrapper
      • Event Api
      • Navigation via JavaScript
      • JavaScript Form Helpers
    • Link handling
      • Link handler configuration
      • LinkBrowser API
      • The LinkHandler API
        • The PageLinkHandler
        • The RecordLinkHandler
        • Implementing a custom LinkHandler
      • Core link handler
      • Frontend link builder
      • LinkBrowser Tutorials
        • Browse records of a table
        • Create a custom link browser
    • Localization
      • Introduction
      • Supported languages
      • Managing translations for backend
      • Translation servers
        • Localization with Crowdin
          • Extension integration
          • Online translation with Crowdin
          • Workflow
          • Frequently Asked Questions (FAQ)
        • Localization with Pootle
        • Custom translation servers
      • XLIFF Format
      • Working with XLIFF files
    • Locking API
    • Logging Framework
      • Quickstart
      • Logger
      • Configuration of the logging system
      • The LogRecord model
      • Log Writers
      • Log processors
    • Mail API
    • Mount points
    • Namespaces
    • Page types
      • Introduction
      • Types of pages
      • X-Redirect-By header for pages with redirect types
      • Create new Page Type
    • Pagination
    • Parsing HTML
    • Password hashing
      • Troubleshooting
    • Request Life Cycle
      • TYPO3 request attributes
        • Application type
        • Frontend controller
        • Frontend user
        • Language
        • Normalized parameters
        • Route
        • Routing
        • Site
        • Target
      • Bootstrapping
      • Middlewares (Request handling)
      • TYPO3 request object
        • Application type
        • Frontend controller
        • Frontend user
        • Language
        • Normalized parameters
        • Routing
        • Site
        • Application type
        • Normalized parameters
        • Route
        • Site
        • Target
    • Routing - "Speaking URLs" in TYPO3
      • Introduction to Routing
      • Page based Routing
      • Advanced routing configuration (for extensions)
      • Extending Routing
      • Collection of various routing examples
    • Rich text editors (RTE)
      • CKEditor Rich Text Editor
      • Rendering in the Frontend
      • Rich text editors in the TYPO3 backend
        • Introduction
        • Plugging in a custom RTE
      • Rich Text Editors (RTE) in the TYPO3 frontend
        • Including a Rich Text Editor (RTE) in the frontend
      • RTE Transformations
        • Introduction
        • Transformation overview
      • Historical Perspective on RTE Transformations
        • Properties and Transformations
        • RTE Transformations in Content Elements
    • Search engine optimization (SEO)
      • Canonical API
      • MetaTag API
      • Page title API
      • XML sitemap
    • Services
      • Introduction
      • Using Services
        • Service precedence
        • Simple usage
        • Use with subtypes
        • Calling a chain of services
      • Configuration
        • Override service registration
        • Service configuration
        • Service type configuration
      • Developer's Guide
        • Introducing a new service type
        • Implementing a service
        • Service API
        • Services API
    • Session handling in TYPO3
      • User session management
      • Session storage framework
    • Site handling
      • Basics
      • Creating a new site configuration
      • Base variants
      • Adding Languages
      • Error handling
        • Page-based error handler
        • Fluid-based error handler
        • Writing a custom page error handler
      • Writing a custom page error handler
      • Static routes
      • Using environment variables in the site configuration
      • Using site configuration in TypoScript
      • Using site configuration in conditions
      • Using site configuration in TCA foreign_table_where
      • Site settings
      • CLI tools for site handling
      • PHP API: accessing site configuration
      • Extending site configuration
    • Soft references
    • Symfony expression language
    • System registry
    • TCE (TYPO3 Core engine) & DataHandler
      • Introduction
      • Database: DataHandler basics (Formerly Known as TCEmain)
      • Using the DataHandler in scripts
      • The "/record/commit" Route
      • File Functions Basics
      • The "tce_file.php" API
    • Versioning and Workspaces
    • XCLASSes (Extending Classes)
  • Coding Guidelines
    • Introduction
    • PHP Coding Guidelines
      • PHP File Formatting
        • General Requirements for PHP Files
        • File Structure
        • PHP Syntax Formatting
        • Using phpDoc
      • PHP Architecture
        • Modeling Cross Cutting Concerns
          • Static Methods, static Classes, Utility Classes
          • Traits
          • Services
        • Working With Exceptions
        • General Links
      • Coding: Best practices
        • Accessing the Database
        • Singletons
        • Static Methods
        • Localization
        • Unit Tests
        • Handling Deprecation
        • Namespaces and Class Names of User Files
        • Hook Naming
    • JavaScript Coding Guidelines
    • TypeScript Coding Guidelines
    • TypoScript Coding Guidelines
    • TSconfig Coding Guidelines
    • Xliff Coding Guidelines
    • Yaml Coding Guidelines
    • reStructuredText (reST)
  • Configuration
    • Configuration overview
    • Glossary
    • Configuration files
    • Configuration module
    • Feature toggles
    • $GLOBALS
    • TYPO3_CONF_VARS
      • BE - backend configuration
      • DB - Database connections
      • EXT - Extension manager configuration
      • FE - frontend configuration
      • GFX - graphics configuration
      • HTTP - tune requests
      • MAIL settings
      • SYS - System configuration
    • Global meta information about TYPO3
    • TSconfig
    • TypoScript syntax
      • What Is TypoScript?
      • Syntax
        • Introduction
        • Contexts
        • TypoScript syntax
        • Conditions
        • Includes
      • Sorting out details
        • Parsing, Storing and Executing TypoScript
        • Myths, FAQ and acknowledgements
      • The TypoScript Parser API
        • Introduction
        • Parsing Custom TypoScript
        • Implementing Custom Conditions
    • User settings configuration
      • ['columns'] Section
      • ['showitem'] section
      • Extending the user settings
      • View the configuration
    • YAML
      • YAML API
      • YAML syntax
      • Services.yaml
  • Extension development
    • Concepts
      • Introduction
      • System and Local Extensions
      • Further reading
    • File structure
      • composer.json
      • ext_conf_template.txt
      • ext_emconf.php
      • ext_localconf.php
      • ext_tables.php
      • ext_tables.sql
      • ext_tables_static+adt.sql
      • ext_typoscript_setup.typoscript
      • Classes
      • Configuration
        • Backend
        • Extbase
          • Persistence
        • TCA
        • TsConfig
        • TypoScript
        • Icons.php
        • RequestMiddlewares.php
        • Services.yaml
      • Documentation
      • Resources
        • Private
          • Language
        • Public
      • Tests
    • Howto
      • Backend modules
        • Backend interface
        • View registered modules
        • Backend module API
        • Backend Template View (Extbase)
        • Backend module API (Extbase)
        • Register a toplevel module (Extbase)
        • The Backend Template View (core)
        • Backend module API (core)
        • Tutorials
      • Events
      • Extending the TCA array
        • Storing the changes
        • Customization Examples
        • Verifying the TCA
      • Frontend plugin
        • AbstractPlugin
      • Localization
        • Multi-language Fluid templates
        • Localization in PHP
        • TypoScript
      • Publish your extension
        • Publish your extension in the TER
      • HTTP requests to external sources
      • Update your extension for new TYPO3 versions
        • Extension scanner
        • Upgrade wizards
          • The concept of upgrade wizards
          • Creating upgrade wizards
      • Configuration
      • Creating a new distribution
      • Creating a new extension
      • Custom Extension Repository
      • Adding documentation
      • Extension management
    • Extbase
      • Extbase introduction
      • Extbase reference
        • Model / Domain
          • Model
          • Persistence
          • Repository
          • Validator
        • Controller
          • ActionController
          • Error action
          • Type converters
        • View
        • URI builder (Extbase)
        • Registration of frontend plugins
        • TypoScript configuration
        • Annotations
        • Validation
        • Caching
        • Localization
      • Extbase Examples
    • Best practises and conventions
      • Choosing an extension key
      • Naming conventions
      • Configuration Files (ext_tables.php & ext_localconf.php)
      • Software Design Principles
    • Tutorials
      • Kickstart an Extension
        • Make
          • Create a new backend controller
          • Create a new console command
        • Sitepackage Builder
          • Minimal extension
      • Tea in a nutshell
        • Create an extension
        • Create a directory structure
        • Model: a bag of tea
        • Repository
        • Controller
  • Security guidelines
    • Introduction
    • The TYPO3 Security Team
    • General Information
    • Types of Security Threats
    • General guidelines
    • Guidelines for System Administrators
      • Role Definition
      • Integrity of TYPO3 Packages
      • File/directory permissions
      • Restrict access to files on a server-level
      • Disable directory indexing
      • File extension handling
      • Content security policy
      • Database access
      • Encrypted Client/server Communication
      • Other Services
      • Further Actions
    • Guidelines for extension development
    • Guidelines for TYPO3 integrators
      • Install tool
      • Global TYPO3 configuration options
      • Security-related warnings after login
      • Reports and logs
      • Users and access privileges
      • TYPO3 extensions
      • TypoScript
      • Content elements
    • Guidelines for editors
    • Backup strategy
    • Detect, analyze and repair a hacked site
      • Detect a hacked website
      • Take the website offline
      • Analyzing a hacked site
      • Repair/restore
      • Further actions
  • Testing
    • History
    • Core testing
    • Extension testing
    • Project testing
    • Writing unit tests
    • Writing functional tests
    • Writing acceptance tests
    • FAQ
  • About This Manual
  • Sitemap
  • Index

PAGE CONTENTS

  • Create a custom link browser
    • 1. Register the custom link browser tab in page TSconfig
    • 2. Create a link browser tab
      • Initialization and dependencies
      • Enable dependency injection
      • Render the link browser tab
      • Set the link via JavaScript
      • Can we handle this link?
      • Format current URL
    • 3. Introduce the custom link format
    • 4. Render the custom link format in the frontend
  1. Start
  2. API A-Z
  3. Link handling
  4. LinkBrowser Tutorials
  5. Create a custom link browser
View source How to edit Edit on GitHub

Display settings


Color scheme of code blocks:


Create a custom link browser¶

In this tutorial we create a custom link browser and the associated backend link handler.

We create a new tab in the link browser window in the TYPO3 backend:

../../../_images/CustomLinkBrowser.png

A custom link browser to link to GitHub issues¶

Tip

If you want to link to a record in a custom table, configure the RecordLinkBrowser. You do not need a custom link browser in that scenario.

We introduce a custom link format to store the links in this format: t3://github?issue=123.

This enables us to edit an existing link in the link browser or to change parts of the GitHub URI programmatically later.

And we render the new link in the frontend automatically.

Step by step to a custom link browser

  • 1. Register the custom link browser tab in page TSconfig

  • 2. Create a link browser tab

    • Initialization and dependencies

    • Enable dependency injection

    • Render the link browser tab

    • Set the link via JavaScript

    • Can we handle this link?

    • Format current URL

  • 3. Introduce the custom link format

  • 4. Render the custom link format in the frontend

1. Register the custom link browser tab in page TSconfig¶

EXT:examples/Configuration/TsConfig/Page/LinkBrowser/GitHubLinkhandler.tsconfig¶
TCEMAIN.linkHandler {
   github {
      handler = T3docs\Examples\LinkHandler\GitHubLinkHandler
      label = LLL:EXT:examples/Resources/Private/Language/locallang_browse_links.xlf:github
      displayAfter = haiku
      scanBefore = url
      configuration {
         project = TYPO3-Documentation/TYPO3CMS-Reference-CoreApi
         action = issues
      }
   }
}

The following options are of note here:

handler

The backend link handler that we create in step 2.

configuration

Some configuration, available to the backend link handler. This information is not available in the frontend. Therefore in the frontend rendering of the link the information must be stored in another way. In this example we hardcoded it. But you could also make it available by TypoScript Setup or as part of the link that is saved.

For a complete list of available option see Link handler configuration.

2. Create a link browser tab¶

To create a link browser tab we implement the interface \TYPO3\CMS\Backend\LinkHandler\LinkHandlerInterface.

All backend link handlers provided by the Core extend the abstract class TYPO3\CMS\Backend\LinkHandler\AbstractLinkHandler. However, this class is marked as @internal and therefore can be changed by the Core Team at any time.

You have the choice of implementing the LinkHandlerInterface yourself by having a look at the AbstractLinkHandler for best practices or to extend the AbstractLinkHandler. In the latter case your code might break on updates though.

In this tutorial, we implement the LinkHandlerInterface directly, as it is best practice not to rely on internal classes.

You can find the complete class in the extension EXT:examples on GitHub: GitHubLinkHandler.

We will explain some of the important methods below:

Initialization and dependencies¶

Class T3docs\Examples\LinkHandler\GitHubLinkHandler¶
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Recordlist\Controller\AbstractLinkBrowserController;
use TYPO3Fluid\Fluid\View\ViewInterface;

class GitHubLinkHandler implements LinkHandlerInterface
{
    protected $linkAttributes = ['target', 'title', 'class', 'params', 'rel'];

    protected $linkParts = [];

    protected $view;

    protected $configuration;

    public function __construct(PageRenderer $pageRenderer)
    {
        $this->pageRenderer = $pageRenderer;
    }

    public function initialize(AbstractLinkBrowserController $linkBrowser, $identifier, array $configuration)
    {
        $this->configuration = $configuration;
    }

    public function setView(\TYPO3Fluid\Fluid\View\ViewInterface $view): void
    {
        $this->view = $view;
    }
}

For technical reasons, not all dependencies needed by the backend link handler can be acquired by Dependency injection. Therefore the following two methods are called by Core classes once the dependencies are available:

LinkHandlerInterface::initialize() takes care of setting the \TYPO3\CMS\Backend\Controller\AbstractLinkBrowserController, the identifier and the configuration information. In this example we only need the configuration, the other parameters might be needed in different scenarios.

AbstractLinkBrowserController $linkBrowser

Is the surrounding class calling the link handler. This class stores configuration information of the complete link browser window.

string $identifier

Contains the key of the page TSconfig configuration of the link browser tab this instance renders.

array $configuration

Contains the page TSconfig configuration as array of the link browser tab this instance renders.

The method setView() is called by the AbstractLinkBrowserController once the view is available and contains the necessary information to render the link browser window.

Note

setView() is not part of the LinkHandlerInterface and its call is an implementation detail that might be changed in the future.

Enable dependency injection¶

Backend link handlers are called internally in the TYPO3 Core by GeneralUtility::makeInstance(). Therefore dependency injection needs to be enabled by marking the class as public in the extension's Configuration/Services.yaml. As we keep internal states in the link handler class (for example $linkParts) it cannot be a singleton and must be marked as shared: false:

EXT:examples/Configuration/Services.yaml¶
services:
  _defaults:
    autowire: true
    autoconfigure: true
    public: false

  T3docs\Examples\LinkHandler\GitHubLinkHandler:
    public: true
    # The link handler keeps a state and can therefore be no singleton
    shared: false

Render the link browser tab¶

The method LinkHandlerInterface::render() is called when the tab should be rendered. It registers the required JavaScript in the page renderer, assigns variables to the view and returns the rendered HTML.

Class T3docs\Examples\LinkHandler\GitHubLinkHandler¶
use Psr\Http\Message\ServerRequestInterface;

class GitHubLinkHandler implements LinkHandlerInterface
{
    public function render(ServerRequestInterface $request): string
    {
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Examples/GitHubLinkHandler');
        $this->view->getRequest()->setControllerExtensionName('examples');
        $this->view->setTemplateRootPaths(['EXT:examples/Resources/Private/Templates/LinkBrowser']);

        $this->view->assign('project', $this->configuration['project'] ?? '');
        $this->view->assign('action', $this->configuration['action'] ?? '');
        $this->view->assign('github', !empty($this->linkParts) ? $this->linkParts['url']['value'] : '');

        $this->view->setTemplate('GitHub');
        return '';
    }
}

Set the link via JavaScript¶

When the button in the rendered form is clicked to set a link, a custom JavaScript class interprets the form data and creates the link to be stored:

EXT:examples/Resources/Public/JavaScript/GitHubLinkHandler.js¶
/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

/**
 * Module: TYPO3/CMS/Examples/GitHubLinkHandler
 * Github issue link interaction
 */
define(['jquery', 'TYPO3/CMS/Recordlist/LinkBrowser'], function($, LinkBrowser) {
     'use strict';

     /**
      *
      * @type {{}}
      * @exports T3docs/Examples/GitHubLinkHandler
      */
     var GitHubLinkHandler = {};

     $(function() {
             $('#lgithubform').on('submit', function(event) {
                     event.preventDefault();

                     var value = $(this).find('[name="lgithub"]').val();
                     if (value === 'github:') {
                             return;
                     }
                     if (value.indexOf('github:') === 0) {
                             value = value.substr(7);
                     }
                     LinkBrowser.finalizeFunction('github:' + value);
             });
     });

     return GitHubLinkHandler;
});

It is important that the JavaScript function calls LinkBrowser.finalizeFunction(). Otherwise no link will be set.

Can we handle this link?¶

The method LinkHandlerInterface::canHandleLink() is called when the user edits an existing link in the link browser. All backend link handlers will be called and can decide if they can handle that link. If so, they should store the provided information to be used in rendering (for example, to fill an input field with the old value).

Class T3docs\Examples\LinkHandler\GitHubLinkHandler¶
class GitHubLinkHandler implements LinkHandlerInterface
{
    public function canHandleLink(array $linkParts): bool
    {
        if (!isset($linkParts['type']) || $linkParts['type'] !== 'github') {
            return false;
        }
        $this->linkParts = $linkParts;
        return true;
    }
}

Format current URL¶

The function LinkHandlerInterface::formatCurrentUrl() is used to preview what the link will look like in the backend, for example, in the upper part of the link browser window.

Attention

LinkHandlerInterface::formatCurrentUrl() is not used to render the link in the frontend.

3. Introduce the custom link format¶

You can find the complete class in the extension EXT:examples on GitHub: GitHubLinkHandling.

Our backend link handler implementation from step 1 saves the link in the custom format t3://github?issue=123 via JavaScript.

This format is only an arbitrary string until we tell TYPO3 how to handle links of the new format by a second class which implements the TYPO3\CMS\Core\LinkHandling\LinkHandlingInterface.

Note

There are two interfaces with very similar names and very different functionality involved here. The \TYPO3\CMS\Backend\LinkHandler\LinkHandlerInterface renders a tab in the link browser window in the backend. Its implementing class is commonly called a "(backend) link handler". Classes implementing the interface TYPO3\CMS\Core\LinkHandling\LinkHandlingInterface handle the introduced link format. Such a class is called a "(core) link handler".

Class T3docs\Examples\LinkHandler\GitHubLinkHandling¶
/**
 * Resolves GitHub Links
 */
class GitHubLinkHandling implements LinkHandlingInterface
{
    protected $baseUrn = 't3://github';

    public function asString(array $parameters): string
    {
        $githubIssue = (int)$parameters['issue'];
        return $this->baseUrn . '?issue=' . $githubIssue;
    }

    public function resolveHandlerData(array $data): array
    {
        return [
            'issue' => (int)$data['issue'],
        ];
    }
}

The method LinkHandlingInterface::asString() creates a string representation from the parameter array.

LinkHandlingInterface::resolveHandlerData() receives the string representation of the link and creates the parameter array from it. For convenience the parameters are already parsed and stored as key-value pairs in an array for you. You can perform further processing here if needed.

4. Render the custom link format in the frontend¶

The link builder, a class extending the abstract class \TYPO3\CMS\Frontend\Typolink\AbstractTypolinkBuilder is called whenever a link is rendered in the frontend, for example via TypoScript .typolink, by the \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typoLink function or by the \TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder.

Class T3docs\Examples\LinkHandler\GithubLinkBuilder¶
use TYPO3\CMS\Frontend\Typolink\LinkResult;
use TYPO3\CMS\Frontend\Typolink\LinkResultInterface;
use TYPO3\CMS\Frontend\Typolink\UnableToLinkException;

/**
 * Builds a TypoLink to a GitHub issue
 */
final class GitHubLinkBuilder extends AbstractTypolinkBuilder
{
    private const TYPE_GITHUB = 'github';

    public function build(
        array &$linkDetails,
        string $linkText,
        string $target,
        array $conf
    ): LinkResultInterface {
        $issueId = trim($linkDetails['value']);
        $issueId = ltrim($issueId, '#');
        $issueId = (int) $issueId;
        if ($issueId < 1) {
            throw new UnableToLinkException(
                '"' . $linkDetails['value'] . '" is not a valid GitHub issue number.',
                // Use the Unix timestamp of the time of creation of this message
                1665304602,
                null,
                $linkText
            );
        }
        $url = self::URL_TEMPLATE . $issueId;

        return (new LinkResult(self::TYPE_GITHUB, $url))
            ->withTarget($target)
            ->withLinkConfiguration($conf)
            ->withLinkText($linkText);
    }
}

The link builder must be registered in ext_localconf.php, so that the correct link builder for the new type can be determined by the calling API:

EXT:examples/ext_localconf.php (Excerpt)¶
$GLOBALS['TYPO3_CONF_VARS']['FE']['typolinkBuilder']['github'] =
    \T3docs\Examples\LinkHandler\GithubLinkBuilder::class;

The function AbstractTypolinkBuilder::build() is called with the link configuration and data from the typolink function. If the link can be rendered, it returns a new \TYPO3\CMS\Frontend\Typolink\LinkResultInterface. The actual rendering of the link depends on the context the link is rendered in (for example HTML or JSON).

If the link cannot be built it should throw a \TYPO3\CMS\Frontend\Typolink\UnableToLinkException.

Attention

The configuration from the page TSconfig configuration (step 1) is not available in the frontend. Therefore the information which repository to use must be stored in another way. In this example we hardcoded it. But you could also make it available by TypoScript setup or as part of the link format that is saved.

  • Previous
  • Next
  • Home
  • Contact
  • Issues
  • Repository

Last updated: Feb 04, 2023 15:59

Last rendered: Feb 04, 2023 16:04

  • TYPO3 Theme 4.7.9
  • DRC v3.0.dev30
© Copyright since 2012 by the TYPO3 contributors
  • Legal Notice
  • Privacy Policy
  • Code of Conduct