News Archive
PhpRiot Newsletter
Your Email Address:

More information

Twitter Bootstrap and the QuickForm2 Callback Renderer

Note: This article was originally published at Planet PHP on 24 September 2011.
Planet PHP

I don't know about you, but for me building html Forms and styling html Forms are maybe the most boring things in web development. It's repetitive and takes a lot of time to do things correctly.

That's why tools like Twitter's Bootstrap and PEAR's html_QuickForm2 can help with this part of our job.

Wouldn't it be nice to have QuickForm2 generate a markup compatible with Bootstrap CSS, so that you could get a nice looking form without to much efforts? Well, that's what I plan to do here.

Bootstrap is a toolkit from Twitter designed to kickstart development of webapps and sites. It includes base CSS and html for typography, forms, buttons, tables, grids, navigation, and more. In this post, I will concentrate on the form stuff.

QuickForm2 on the other hand is a PHP library dedicated to make building html forms easier, faster and less error-prone. It is hosted in PEAR and has been extensively tested.

First, I will try to build the same form as shown on Bootstrap's website, with QuickForm2. Except for the three elements with appended and prepended things, it was easy. I will come back to these elements later, just know it is not difficult to render them neither.

So here is the result :
Step 1 : Bootstrap with QuickForm2 and no renderer

The most obvious problem is that QuickForm2 doesn't use the same markup to build forms as what Bootstrap expects. To solve this, we can use the Callback renderer that comes with QuickForm2 and define our own callback to render our elements the way Bootstrap likes them.

The Callback renderer associates PHP callbacks with form elements using either their type (text, textarea, a) or their name if you need a more precise control. This means that we can first define how our form object should be rendered, as well as our Checkboxes, Textareas, etc. Adding a Callback renderer and specifying a function to render an element is as simple as that :

$r = html_QuickForm2_Renderer::factory('callback'); A $r-setCallbackForClass('html_QuickForm2_Element', function($renderer, $element) { $error = $element-getError(); if ($error) { $html[] = ''; $element-addClass('error'); } else { $html[] = ''; } $html[] = $renderer-renderLabel($element); $html[] = ''.$element; if ($error) "/

Truncated by Planet PHP, read more at the original (another 7217 bytes)