[Drupal] How to make a vocabulary in one content type as single select and in another as multiple in Drupal 6
In Drupal 6, the configuration of vocabulary itself has an option to specify the content types that requires this vocabulary. There is only global settings for the vocabulary. If we set the vocabulary as multiple select, it will apply to all of the content types to which it belongs. We can not set this field as multiple select in one content type and single select in others.
In one of my project, I had a requirement to make the vocabulary as single select in one of my content type event. But for other content types it should be multiple select. I have found a solution for this by implementing the hook_form_alter. To do this first make the vocabulary as multiple select in the configuration option of the vocabulary. Then do the following steps to make the vocabulary as single select in event content type only.
-
Use the following function to get the vocabulary id of our vocabulary by name.
/** * To get the vocabulary id of a vocabulary from name. */ function mymodule_get_vocab_id_byname($vocabulary_name) { $result = db_query("SELECT vid FROM {vocabulary} WHERE name = '%s'", $vocabulary_name); $vid = db_fetch_object($result)->vid; if($vid) { return $vid; } else { return FALSE; } }
-
Suppose that our vocabulary name is 'Category'. Then implement the form_alter hook as follows to make the vocabulary as single select in the event content type.
/** * Implements hook_form_alter(). * To implement single select using the vocabulory id. */ function mymodule_form_alter(&$form, &$form_state, $form_id) { $vid = mymodule_get_vocab_id_byname('Category'); if ($vid) { if ($form_id == 'event_node_form') { $form['taxonomy'][$vid]['#multiple'] = 0; // Setting for single select } } }
The above code will take the vocabulary id of our vocabulary from the database. If the form is event_node_form, then make the $form['taxonomy'] field as a single select, by setting its multiple attribute ($form['taxonomy'][$vid]['#multiple']) to zero. Now the vocabulary field will behave as a single select in event content type and as multiple select in the other content types.