Works with vocabulary onto Drupal forms

VOCABULARY SELECT FIELD FORM

I have a vocabulary called 'Type Book' and i'll construct a selection field with this vocabulary.


function room_booking_form($node, &$form_state) {

$list = taxonomy_get_tree(taxonomy_vocabulary_machine_name_load('type_of_reservation')->vid);
if (count($list)){
$dropdown_array = array('0' => '--none--');
foreach ($list as $item) {
$key = $item->tid;
$value = $item->name;
$dropdown_array[$key] = $value;
}
$form['booking_type'] = array(
'#weight' => '1',
'#key_type' => 'associative',
'#multiple_toggle' => '1',
'#type' => 'select',
'#options' => $dropdown_array,
'#title' => 'Booking Type',
'#default_value' => isset($node->booking_type) ? $node->booking_type : 0,
);
unset($dropdown_array);
}

WITH HELPER FUNCTION


/**
* helper function to get taxonomy term options for select widget
* @arguments string $machine_name: taxonomy machine name
* @return array of select options for form
*/
function MYMODULE_get_tax_term_options($machine_name){
$options = array( '0' => '');

$vid = taxonomy_vocabulary_machine_name_load($machine_name)->vid;

$options_source = taxonomy_get_tree($vid);

foreach($options_source as $item ) {
$key = $item->tid;
$value = $item->name;
$options[$key] = $value;
}

return $options;
}

Then you can call this function on your #options in your $form:

$form['field_name'] = array(
'#options' => MYMODULE_get_tax_term_options('taxonomy_machine_name'),
);

TO CREATE A VOCABULARY USING CODE


Into MODULE.install file.


/**
* Implements hook_uninstall().
*/
function MODULE_uninstall() {
if($vocabulary = taxonomy_vocabulary_machine_name_load('example_vocabulary'))
{
taxonomy_vocabulary_delete($vocabulary->vid);
}
}

/**
* Implements hook_install().
*/
function MODULE_install() {
node_types_rebuild();
$types = node_type_get_types();
node_add_body_field($types['reserva'],'Descripcion');

$vocabulary = (object) array(
'name' => 'Example',
'machine_name' => 'example_vocabulary',
'description' => t('Example Vocabulary created with reserva_sala module'),
);
taxonomy_vocabulary_save($vocabulary);

$vid = taxonomy_vocabulary_machine_name_load('example_vocabulary')->vid;
// Create vocabulary terms

$edit = array(
'name' => t('Term1'),
'description' => '',
'parent' => array(0),
'vid' => $vid,
);
$term = (object) $edit;
taxonomy_term_save($term);

$edit = array(
'name' => t('Term2'),
'description' => '',
'parent' => array(0),
'vid' => $vid,
);
$term = (object) $edit;
taxonomy_term_save($term);

$edit = array(
'name' => t('Term3'),
'description' => '',
'parent' => array(0),
'vid' => $vid,
);
$term = (object) $edit;
taxonomy_term_save($term);
}