How to add a tooltip to a field label

Someone just asked me why "it is not possible in Backpack to add a question icon next to each field, with a tooltip for more info...

Cristian Tabacitu
Cristian Tabacitu
Share:

Someone just asked me why "it is not possible in Backpack to add a question icon next to each field, with a tooltip for more info on how to complete that field". I realized... it's possible... but it's not documented anywhere. It's something that you know is possible only if you know a bit more about how Backpack works, or tinker to find out.

So let's dispel that myth. Here's a quick tip on how to achieve this:

Backpack field tooltip

First of all, you can easily customize the field label using ->label(). I'm sure you know that. But did you know... that the label output is NOT escaped? That means you can include HTML in the label too.

To achieve the above ASAP, I just went for a quick and dirty solution:

CRUD::field('nickname')->label('Nickname <span class="badge badge-pill bg-gray"><i class="la la-question" data-bs-toggle="tooltip" title="Some details here to help the user fill in the field."></i></span>');

Of course, you can clean it up quite a bit, with a little effort. And if you use this more than once, you'll 100% want to put all that HTML in a single place, and re-use it. But where? Well for example, I usually have a bunch of custom project helpers in app/helpers.php, so I can just add a new helper there:

if (!function_exists('bp_tooltip')) {
    /**
     * Echo a grey badge with a question icon and a tooltip on hover.
     *
     * @param string $string
     *
     * @return string
     */
    function bp_tooltip(string $string)
    {
        return '<span class="badge badge-pill bg-gray"><i class="la la-question" data-bs-toggle="tooltip" title="'.$string.'"></i></span>';
    }
}

And then in your CrudController you can have a much cleaner label:

CRUD::field('nickname')->label('Nickname '.bp_tooltip('Some details here to help the user fill in the field'));

Best of all? If you change the HTML, it changes everywhere. And that's it. That's how you add a tooltip to a field.

Quick note - do NOT confuse this with hint. All Backpack fields also come with a ->hint() method, which adds a grey line of text with details below the field:

Backpack field hint

In most cases, if an explanation is needed, I find it's better to add it as a hint. Sometimes, a tooltip is better. You do you ๐Ÿ˜‰

Hope it helps. Cheers!

Want to receive more articles like this?

Subscribe to our "Article Digest". We'll send you a list of the new articles, every week, month or quarter - your choice.

Reactions & Comments

What do you think about this?

Just a quick heads up, images from this tips and tricks are not loading in!
Damn. How 'bout now? After a hard refresh?
Now it works perfectly! :D

Latest Articles

Wondering what our community has been up to?