Programmatically create vocabulary

Printer-friendly versionSend to a DeveloperPDF version

Imagine a situation in which you are developing a custom module and would like to create a vocabulary when ever your module is installed on a Drupal site. You can instruct the user to create a vocabulary with desired name and settings but the best approach to this situation is to create a vocabulary from the code and populate it with terms right within the module you have developed. This will reduce dependency and the user need not have to configure it manually. This will result in more use of module.

To create a vocabulary using the code you need the function taxonomy_save_vocabulary($vocabullary)
where $vocabullary is an associative array containing information about the vocabulary being created.
The $vocabulary would be:

<?php
$vocabulary
= array(
 
'name'  => t("Currency"). //Human readable name of the vocabulary
 
'multiple' => 0, //set 1 to allow multiple selection
 
'required' => 0, //set 1 to make the terms mandatory to be selected
 
'hierarchy' => 0, //set 1 to allow and create hierarchy of the terms within the vocabulary
 
'relations' => 0, //set 1 to set and allow relation amongst multiple terms
 
'module' => 'mymodule', //provide the module name in which the vocabulary is defined and which is calling this function
 
'node' => array('mymodule' => 1), //set the node to which this vocabulary will be attached to
 
'weight' => -9, //set the weight to display the vocabulary in the list
);

taxonomy_save_vocabulary($vocabulary); //saving the $vocabulary array will create a vocabulary named "Currency". Note the t() in the 'name', this will allow to translate the vocabulary name to different languages.
?>

The advantage of creating the vocabulary programmatically is to eliminate to configure the vocabulary manually after installing the module. This is like carrying everything with you what ever you need.

You feedback is highly appreciated.

Syndicate content

Recent comments

toolbar powered by www.mit3xxx.de