Convert z3c.form field desc. to tooltip

Let’s say you have a typical form with some input fields. By default z3c.form displays a description (if provided in form definition) above each form field, like in the screenshot below for example:

Original form

Sometimes however, you might want to make things a little bit different. Perhaps you want to save some screen space by hiding field descriptions, but still want to provide helpful additional information on form fields to your users. One way of achieving this is to display field descriptions as tooltip text:

Modified form with tooltips

Not bad.

And it’s easy too. Simply set the title attribute of a corresponding form field and you’re done.

I’ll show you how we did it for one of our clients. The form was called List Events, because, well, it lists upcoming events based on search criteria.

# file eventlist.py in browser directory
...
from z3c.form import form
...

class ListEventsForm(form.Form):
    ...

    def updateWidgets(self):
        """Move fields' descriptions to title attributes of HTML form elements."""
        super(ListEventsForm, self).updateWidgets()
        for name, widget in self.widgets.items():
            widget.title = widget.field.description

In the ListEventsForm class we override the updateWidgets method in order to iterate through all form fields and set their title attribute.

Note that this makes tooltips to show, but field descriptions themselves are still visible. We hide them with the following CSS rule (“eventlist-form“ being our form’s ID):

#eventlist-form div.formHelp {
    display: none;
}

And that’s all, folks!