How to: form alter a field label
I seem to vaguely recall the days of D5 when altering fields seemed much simpler.. hmmm. Anyway, needed to alter a simple label of a field today and took far longer than it should have; so thought I would post here. Example Case: node type: Match field: field_match_team1_pts todo: want to change the label on the field based on the value that exists in another field on this node (so this will only occur on a node/edit as the other field will be filled in at this time) To start with many things now need to be modified in a separate #after_build routine rather than directly during the form_alter hook.
<?php
function mymodule_form_alter($form, $form_state, $form_id) {
if ($form_id == 'match_node_form') {
$form['#after_build'][] = '_osp_alter_match_form';
}
return;
}
?>
Then the confusing part. What do I actually modify to change the field's label? As it turns out the more obvious $form array elements:
<?php
$form['field_match_team1_pts']['#title']
$form['field_match_team1_pts'][0]['#title']
?>
which both exist; sadly do not do the trick. But digging a bit more into the $form array for this element we find:
<?php
$form['field_match_team1_pts'][0]['value']['#title']
?>
this is the one we need. So example code ended up like this:
<?php
function _osp_alter_match_form($form, $form_state) {
$node = $form['#node'];
$team1 = node_load($node->field_match_team1[0]['nid']);
$team2 = node_load($node->field_match_team2[0]['nid']);
$form['field_match_team1_pts'][0]['value']['#title'] = "Points for $team1->title";
$form['field_match_team2_pts'][0]['value']['#title'] = "Points for $team2->title";
return $form;
}
?>
Comments (1)
Add Comment