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.
- Make sure to load the tooltip/tooltip library
- Add a data-tooltip attribute on one element, either:
- using a HTML content
- 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';Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.