How to create a Tooltip in PHP

Last updated on
7 April 2022

This page is an example of how to use the Tooltip module in Drupal.

To add a tooltip programmatically is basically the same as to add a tooltip in Twig directly but using of Drupal's Render API in PHP.

  1. Make sure to load the tooltip/tooltip library
  2. Add a data-tooltip attribute on one element, either:
    1. using a HTML content 
    2. referencing a block by its ID or UUID

Note that the block does not have to be placed on the page. The Tooltip library will make an Ajax call to retrieve the block's content for you, respecting the block's access condition.

Render a Tooltip with custom HTML content:

$account = \Drupal::currentUser();

// Prepare a custom advanced HTML content.
$content = [];
$content['intro'] = [
  '#markup' => t('This is the tooltip content'),
];
$content['visible_anonymous_only'] = [
  '#type' => 'link',
  '#title' => t('Log in'),
  '#url' => \Drupal\Core\Url::fromRoute('user.login', [], [
    'query' => [
      'destination' => Url::fromRoute('<current>')->setAbsolute(TRUE)toString(),
    ],
  ],
  '#access' => $account->isAnonymous(),
];
$content['visible_logged_in_only'] = [
  '#markup' => t('It is so cool to be a logged in user!'),
  '#access' => !$account->isAnonymous(),
];


// Create the tooltip element now.
$form['tooltip'] = [
  '#type' => 'inline_template',
  '#template' => '<i class="icon icon-info" data-tooltip="{{ settings }}"></i>',
  '#context' => [
    'settings' => \Drupal\Component\Serialization\Json::encode([
      'content' => \Drupal::service('renderer')->renderPlain($content),
      'placement' => 'bottom',
    ]),
  ],
];

$form['#attached']['library'][] = 'tooltip/tooltip';

Render a block in a Tooltip:

use Drupal\Component\Serialization\Json;

$block_id_or_uuid = 'tooltip_custom_block_id';

$form['tooltip'] = [
  '#type' => 'inline_template',
  '#template' => '<i class="icon icon-info" data-tooltip="{{ settings }}"></i>',
  '#context' => [
    'settings' => Json::encode([
      'block' => $block_id_or_uuid,
      'placement' => 'bottom',
      'modifiers' => [
        // Pixel-perfect the tooltip position.
        ['name' => 'offset', 'options' => ['offset' => [null, 8]]],
      ],
    ]),
  ],
];

$form['#attached']['library'][] = 'tooltip/tooltip';

Tags

Help improve this page

Page status: No known problems

You can: