Advanced Drupal 7 Form Element Theming

Posted on Feb. 28, 2013

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 theme_checkbox() function? 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.

Learning Drupal? Subscribe to my Drupal articles, tips and tutorials.

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 here. Be sure to replace the word theme with example.

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
<?php
if ($element['#type'] == 'checkbox') {
  $variables['rendered_element'] = ' ' . $prefix . $element['#children'] . $suffix . "\n";
  $output .= theme('form_element_label', $variables);
}
else {
  switch ($element['#title_display']) {
    case 'before':
    case 'invisible':
      $output .= ' ' . theme('form_element_label', $variables);
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;

    case 'after':
      $output .= ' ' . $prefix . $element['#children'] . $suffix;
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
      break;

    case 'none':
    case 'attribute':
      // Output no label and no required marker, only the children.
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;
  }
}

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 the existing theme_form_element_label() from here and changing theme to 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
<?php
// Bootstrap wants us to add a class to the label as well.
if ($element['#type'] == 'checkbox') {
  $attributes['class'] = 'checkbox';
}

// The leading whitespace helps visually separate fields from inline labels.
if (!empty($variables['rendered_element'])) {
  return ' <label' . drupal_attributes($attributes) . '>' . $variables['rendered_element'] . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
}
else {
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
}

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:

1
2
<?php
_form_set_class($element, array('form-checkbox', 'checkbox'));

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.

Comments

BoyMarch 1, 2013, 2:06 a.m.

Good!

Reply
MarcMarch 1, 2013, 7:47 p.m.

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.

Reply
henrikakselsenMarch 8, 2013, 3:29 p.m.

dat font!

Reply
Noah WalkerApril 20, 2019, 9:40 a.m.

Elements of the themes are usually having troubles to joining and then getting some checking of the boxes with the figure out. Themes will not be implements on the system from the college paper.org website when only drupe themes will surround it.

Reply
fggfggfMay 18, 2019, 2:30 p.m.

Le vendeur doit devenir un homme sage qui parle bien: il utilisera le langage le plus ingénieux pour parler au cœur de son interlocuteur et développer sans problème un canal de vente performant. Replique Rolex Montre Par conséquent, la capacité d'apprendre à parler peut profondément attirer les clients et satisfaire la psychologie de l'écoute des clients, de manière à susciter l'intérêt et l'attention des clients. En tant que vendeur, lorsque vous parlez à vos clients, si ceux-ci sont hésitants, vous devez réfléchir à vous-même et déterminer si vous avez des problèmes pour présenter les produits aux clients. Le client introduit n'est pas très clair.

Reply
SteveJune 7, 2019, 5:42 p.m.

I truly appreciated the way you inscribe this info message thank you for sharing this Wonderful information. Homestyle Renovation Loan

Reply
Ethan CampbellJune 26, 2019, 6:46 a.m.

When you get to that level you may not consider Drupal, Wordpress, Ruby/Radiant, python/Django. But most likely start to transition to platforms such as Java/Alfresco or Csharp/DNN. The platform is a factor, but not the primary guiding pro dissertation help driver as you then need to consider the infrastructure strategy as well. Network/Server architecture plays a key roll as does your multi-level caching strategy.

Reply
cleaning servicesJune 30, 2019, 1:11 p.m.

Before you'll sign that contract it will be quite natural that you really remain serious about receiving a homogenous performance belonging to the company within the entire term belonging to the contract. So, negotiate acceptable terms along with for a powerful agreement fo you to terminate that contract for everybody who is not satisfied with their expertise. cleaning services

Reply
Martin StoneJuly 18, 2019, 6:31 a.m.

In Drupal 6 and past, topic creators would now be able to tweak this page by adding extra settings to the structure. In Drupal 5, Pay To Write A Research Paper subject creators and topic clients should introduce the Theme Settings API module...

Reply
online shopping Store in pakistanJuly 23, 2019, 5:05 p.m.

YesOnline is one of the best Online Shopping Store in Pakistan . We provide quality fashion wear for women. We provide them at the best price.

Reply
Atif HassanJuly 26, 2019, 7:53 a.m.

The codes seem so interesting I hope it will work in my assignment and if I get success in making my coding assignments then I will be very grateful to you. And If I still stuck in the problem then I will use assignment writing services to solve it for gaining marks.

Reply
paulSept. 4, 2019, 7:03 p.m.

I need to know some urgent details about something, and I hope you help me with that. The details about https://altomerge.com/faq are needed by me right now, and I want you to share these details with me as soon as possible.

Reply
susan mayerSept. 5, 2019, 3:09 a.m.

This content is written very well. Your use of formatting when making your points makes your observations very clear and easy to understand. Thank you. things to do post

Reply
fndSept. 9, 2019, 9:17 a.m.

酒酿蛋,对于女性是非常有好处的丰胸产品。酒酿蛋顾名思义就是用酒酿的蛋。是有着非常大的功效的丰胸达人。酒酿蛋的主要做法就是要准备好酒酿蛋3大勺丰胸产品粉嫩公主,鸡蛋蛋清1个,清水适量,红糖适中。做法就是在滚水中加入红糖,然后在打入鸡蛋。再将各种材料放入锅中丰胸最快方法。就能做好了。

Reply
donSept. 12, 2019, 8:52 a.m.

There are a number cloud technology of websites that really help readers a lot. Try adding more useful ideas through this page. A good collection of these relevant ideas makes the page one of the best. The good collection of such useful topics makes the page truly impressive.

Reply
rickSept. 13, 2019, 7:26 p.m.

Thanks for sharing this quality information with us. I really enjoyed reading. Will surely going to share this URL with my friends SDigital signature class 2

Reply
johnSept. 18, 2019, 3:34 p.m.

This advanced drupal element theming sounds really interesting to me, and I will try this out once I find more here about this scheme. I just need to ensure that this scheme works, and you are not making a fool out of me.

Reply
davidSept. 22, 2019, 2:34 p.m.

Employment Provident Fund Organisation (EPFO) has provided the facility for Epf account holders, who have lost/ forgotten the UAN (Universal Account Number) number. So, if you want to recover or reset your UAN password or any queries like, epfo forgot password, Mobile number change, UAN Password not working, Reset UAN Login Password, etc. we have provided the information on how to reset or change the UAN number with your registered mobile number. Forgot UAN Password

Reply

Post New Comment