Creating select form using Taxonomy and Form API
Creating select form using Taxonomy and Form API
Often times when using the Drupal Form API creating custom forms, you'll need to get a select list of Taxonomy terms as options. These snippets will help you look up terms in a vocabulary and put them in your options array.
Drupal 8
// Create empty options array
$options = array();
// Taxonomy vocabulary machine name
$taxonomy = 'tax_machine_name';
// Get all the taxonomy terms from the vocabulary
$tax_items = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($taxonomy);
// Inject into the options array
foreach($tax_items as $tax_item) {
$options[$tax_item->tid] = $tax_item->name;
}
// Create a select form element
$form['taxonomy_options'] = array(
'#type' => 'select',
'#options' => $options,
'#required' => TRUE,
);
Drupal 7
// Create empty options array
$options = array();
// Taxonomy vocabulary machine name
$taxonomy = 'tax_machine_name';
// Get all the taxonomy terms from the vocabulary
$vocab = taxonomy_vocabulary_machine_name_load('tax_machine_name')->vid;
$tax_items = taxonomy_get_tree($vocab);
// Inject into the options array
foreach($tax_items as $tax_item) {
$options[$tax_item->tid] = $tax_item->name;
}
// Create a select form element
$form['taxonomy_options'] = array(
'#type' => 'select',
'#options' => $options,
'#required' => TRUE,
);