background image

Content tagged with: label

Eric's picture

Hardcoding something in your module or theme can be just as bad as hacking the core. If the Drupal admin interface allows you the change and configure something, your modules and themes must be scalable enough to account for these changes. This code snippet (example) shows you how you can lookup the CCK field labels, so you'll never have to hard code a label in your theme/module again.

<?php
// create a container for the field labels
$fieldLabels = array();

// load node
$node = node_load('MYCCKNODEID');

// loop through node properties
foreach ($node as $k => $v) {
 
// ensure this property is a field
 
if (substr($k,0,6) == 'field_') {
   
// use the CCK function to get the field data for this field
   
$fieldData = content_fields($k, $node->type);

   
// add the label to the array
   
$fieldLabels[$k] = $fieldData['widget']['label'];
  }
}

// for debug, you could now show all the fields with their labels:
echo "<pre>";
print_r($fieldLabels);
echo
"</pre>";
?>

Eric's picture

Normally when there is a form input error, Drupal highlights the form input by adding a red border and changing the text color. Unfortunately, nothing happens for checkboxes and radio buttons. Here's a little jQuery to add the error class to the label directly above a set of checkboxes or radios when an error occurs.

<?php
$('form#node-form div.form-item').each(function(){
  var
result = 0;
 
result += $(this).find('div.form-radios input.form-radio.error').length;
 
result += $(this).find('div.form-checkboxes input.form-checkbox.error').length;
  if (
result) $(this).find('label:first').removeClass('error').addClass('error');
});
?>

Eric's picture

You may have noticed that if you create a custom node type that has uses the radios widget, there is no visual error indicator attached to the radios. I added some jQuery to my theme to highlight the label of the radios when there is an error associated with them.

<?php
$(document).ready(function(){
  $(
'form#node-form div.form-item').each(function(){
    var
result = $(this).find('div.form-radios input.form-radio.error').length;
    if (
result) {
      $(
this).find('label:first').removeClass('error').addClass('error');
    }
  });
});
?>