changing title of a node

Last modified: August 20, 2006 - 16:27

In some cases you want to construct the title of a CCK node automatically, for example, you may want to construct it from other values on the form.

<?php
function mymodule_form_alter($form_id, &$form) {
 
// Check if we are on a node editing form for our type.
 
if (isset($form['#node']) && ($node = $form['#node']) && $form_id == $node->type .'_node_form') {
    if (
$node->type == 'type-to-change') {
     
// As we are going to construct the title ourself, there should
      // not be any edit box for the title. As there is still a validator
      // on the title field, we need to input a dummy value.
     
$form['title']['#type'] = 'value';
     
$form['title']['#value'] = 'this will not be used';
    }
  }
  return
$form;
}

function
mymodule_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  if (
$op == 'validate' && $node->type == 'type-to-change') {
   
// We can change the value of the title in the validate hook
    // for nodes. The form is actually passed as 3rd parameter
    // to hook_nodeapi() for $op == 'validate'.
   
$form = $teaser; //messy
   
form_set_value($form['title'], 'some new value');
  }
}
?>

After some discussion with chx on #drupal, this seemed like the best solution.

 
 

Drupal is a registered trademark of Dries Buytaert.