Posted on 2013-02-28 23:22:00+00:00
Ever wanted to give form elements a custom look? Theming entire forms is straightforward, if laborious. But theming individual textboxes, checkboxes and radio buttons is slightly more obscure. Keep reading to find out how to fully customize your form elements, from the input itself to the label.
You might be wondering: can't I just implement a
Well, that might meet your requirements, but this doesn't handle the label at
all. Let's set up our theme to give us maximum flexibility.
Let's start with a use case: Bootstrap likes to have checkboxes inside the label element. I happen to like this markup too. But Drupal places the checkbox next to the label. How can we achieve this without hacking core?
Start by copying over
theme_form_element() into the
template.php file in
your theme. Let's assume the theme is called
example. You can find the body
Be sure to replace the word
Now find the switch statement and replace it to look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Notice we wrapped it with an outer
if statement. Here, we a define custom
behavior for our checkbox. This allows us to give checkboxes special handling
for labels using a custom
theme_form_label(). Let's implement that, by copying
theme_form_element_label() from here
example. But let's make a change. Remove the return
statement (and the comment above it) and replace it with:
1 2 3 4 5 6 7 8 9 10 11 12 13
Last but not least, Bootstrap also likes us to add the class
checkbox to the
input element itself. Though this isn't necessary for any CSS rules, the
guide shows the
markup this way. So it's best to be safe. We do this by overriding the
theme_checkbox() function. Change the
_form_set_class() function call to:
And that's it. You now have a fully themed Bootstrap checkbox. More importantly, adding future elements and theming is very quick. You only need to set up all these theme functions once.
Check out the full
template.php file for reference.
Could you guys join http://drupal.org/node/1114398, please? This fixes a lot of broken form theming. It could all be a lot easier if this bugs would not exist.