I have 2 content types and when nodes get created from both of these, they can sometimes have the same name (title). This causes problems of distinction when referencing nodes from fields that can reference both types.
What I would like to do is append to the title the name of the content type in parenthesis whenever a node gets created (NOT EDITED) from one of these content types.
So for example, say we have content types “Foobar A” and “Foobar B”. Now let’s assume that we create a node with the title of “Blah” from both content types. Now whenever a node is referenced from a reference field that allows referencing from both content types, you’ll see “Blah” come down twice in the drop-down. Instead, I would like to see something like “Blah (Foobar A)” and “Blah (Foobar B)” as options.
So, long story short, how do I manipulate the node title value before it’s submitted to the database IF and ONLY IF the originating node is being CREATED and NOT EDITED? What API functions will I need to achieve this?
Never mind. I figured it out…
Here’s how I did it for Drupal 7.x: Inside template.php, I added the following code:
function [I]<template name>[/I]_form_alter(&$form, &$form_state, $form_id){
if($form_id == '[I]<content type>[/I]_node_form'){
$form['#submit'][]="page_submit";//Name of the submit callback function, which is needed to manipulate the data before being inserted into the database ex post facto form submit.
}
}
//Submit callback function--this is where the data is changed!
function page_submit(&$form, &$form_state){
//If the title of the submitted page doesn't have ' (FOOBAR!) at the end, add it...
if(substr($form_state['values']['title'],-10,10) !== ' (FOOBAR!)'){
$form_state['values']['title'] = $form_state['values']['title'].' (FOOBAR!)';
}
}
I added all this into template.php much to the chagrin of all the IIRC advice I received. My rationale for doing this is that it keeps my code in one spot more so than it would had I followed their advice and placed it all into a separate module. To each, their own, right? It just makes it easier to mess with IMO and since the change here isn’t very big, I don’t believe there’s much to worry about with state separation.
Yeah, to each their own… I tend to work within template.php often so that my modules directory isn’t cluttered with tiny helper modules but I can see the argument to use hook_form_alter in a module too.
I suspect the dev’s who were unsupportive of your decision were thinking that you’d incur less overhead by stuffing it in a module so that it gets processed with the business logic rather than during presentation rendering. For me it depends on the site and how hard the site has to work.