D7 - Converting Title field in a cutom content type to a select List

awm's picture

Hello everyone,

I had a requirement to create a custom content type in D7 where the user can choose the title from a predefined select list.
I did create the content type but to my surprise the title field is not editable and no widget can be selected. However, I attempted to modify the title field by creating a module. I was successful to convert the title field to a select list with predefined options/values and it works fine when adding a new node. But when I try to edit an existing node, the previously selected title does not load but rather the default/empty option.
Note that the node itself does not lose the information but somehow the information is not passed correctly to the form when I try to edit it.
here is the code:

<?php
function customtitle_form_alter(&$form, &$form_state, $form_id){
    if(
$form_id == 'article_node_form'){
       
$form['title'] = array(
           
'#type' => 'select',
           
'#title' => 'Country Name',
           
'#empty_option' => 'Select',
           
'#default_value' => !empty($node->title) ? $node->title : '',
           
'#required' => TRUE,
           

           
'#options' => array(
                   
               
                   
'Afghanistan' =>'Afghanistan',
                   
'Albania' =>'Albania',
                   
'Algeria' =>'Algeria',
                   
'Andorra' =>'Andorra',
                   
'Angola' =>'Angola',
                   
'Antigua and Barbuda' =>'Antigua and Barbuda',
                   
'Argentina' =>'Argentina',
                   
'Armenia' =>'Armenia',
                   
'Australia' =>'Australia',

                        ),
           
         
        );
       
    }
}
?>

Also, as you may see, I did not write a custom submit because there is no need to since I am just modifying an existing content type.

Any idea is much appreciated

-Ali

Comments

I just figured it out. The

awm's picture

I just figured it out. The problem was with '#value_callback' . To solve it i had to set '#value_callback' => 'myelement_value' where my_element_value is a function

<?php
function myelement_value($element, $input = FALSE, $form_state = array()) {
  if (
$input === FALSE) {
    return isset(
$element['#default_value']) ? $element['#default_value'] : $form_state['node']->title;
  }
}
?>

I actually went through the forms api and saw the value_callback documentation. But it was not very clear, well, at least to me. Hope this well help others.

Cheers

Ali