
Drupal 7: Assigning vocabularies with Field API
This took me far too long to figure out, but here's how you create a vocabulary, and then a taxonomy field and instance, all through an .install file (or anywhere else you really care to put it). Took a bunch of debugging before I hit on the right magical combination. This is part of a demo I'm working on for the Drupal 7 and FRBR mental model I published last night.
$libdb_vocabulary_endeavorers = (object) array(
'name' => 'Endeavorers',
'machine_name' => 'libdb_endeavorers',
'description' => t('FRBR Group 2 entities: Persons and Corporate Bodies.'),
'help' => t('Enter a comma-separated list of persons or corporations.'),
);
taxonomy_vocabulary_save($libdb_vocabulary_endeavorers);
$vocabularies = taxonomy_vocabulary_get_names();
$libdb_m_group2_field = array(
'field_name' => 'libdb_m_authors',
'type' => 'taxonomy_term',
'cardinality' => FIELD_CARDINALITY_UNLIMITED,
'settings' => array(
'allowed_values' => array(
array(
'vid' => $vocabularies['libdb_endeavorers']->vid,
'parent' => 0,
),
),
),
);
$libdb_m_group2_instance = array(
'field_name' => 'libdb_m_authors',
'object_type' => 'node',
'label' => 'Authors',
'bundle' => 'libdb_book',
'required' => TRUE,
'description' => t('Enter a comma-separated list of persons or corporations.'),
'widget' => array(
'type' => 'taxonomy_autocomplete',
),
);
field_create_field($libdb_m_group2_field);
field_create_instance($libdb_m_group2_instance);

