Code snippet: How to force uppercase in CCK fields
Last modified: May 3, 2009 - 02:27
Following How to set the disabled attribute of a CCK field I came up with this code to force the use of uppercase with CCK fields.
The code it's almost the same as from How to set the disabled attribute of a CCK field, I'm just changing the attribute to load some javascript. Also, change 'myalter' to your module name.
I'm altering two text fields, 'field_firstname' and 'field_lastname', you can add more fields if you like. Don't forget that if you're using fields inside a group (fieldset) you have to define the fieldset first. See the code.
<?php
/**
* @file
* Form Alter to Transform fields values to Uppercase
*/
function myalter_form_alter(&$form, $form_state, $form_id) {
if (isset($form['type']) && isset($form['#node'])) {
// Use this check to match node edit form for a particular content type.
if ('miembro_node_form' == $form_id) {
$form['#after_build'][] = '_myalter_after_build';
}
// Use this check to match node edit form for any content type.
// if ($form['type']['#value'] .'_node_form' == $form_id) {
// $form['#after_build'][] = '_mysnippet_after_build';
// }
}
}
/**
* Custom after_build callback handler.
*/
function _myalter_after_build($form, &$form_state) {
// Use this one if the field is placed on top of the form.
_myalter_fix_disabled($form['field_firstname']);
_myalter_fix_disabled($form['field_lastname']);
// Use this one if the field is placed inside a fieldgroup.
// _mysnippet_fix_disabled($form['group_mygroup']['field_myfield']);
return $form;
}
/**
* Recursively set the disabled attribute of a CCK field
* and all its dependent FAPI elements.
*/
function _myalter_fix_disabled(&$elements) {
foreach (element_children($elements) as $key) {
if (isset($elements[$key]) && $elements[$key]) {
// Recurse through all children elements.
_myalter_fix_disabled($elements[$key]);
}
}
if (!isset($elements['#attributes'])) {
$elements['#attributes'] = array('onblur' => "{this.value = this.value.toUpperCase();}");
}
$elements['#attributes'] = array('onblur' => "{this.value = this.value.toUpperCase();}");
}
?>Thanks to markus_petrux for the code.
