The solution was to create a module that adds an 'enabled' property to term entities and implements a version of the 'autocomplete' widget with a custom callback to filter the results.
hook_schema_alter() tells Drupal that the entity has the new property but we have to manually add the database column in hook_install() and remove it in hook_uninstall().
/*
* Implements hook_schema_alter() - adds boolean field to disable terms by default
*/
function term_disabler_schema_alter(&$schema) {
$schema['taxonomy_term_data']['fields']['enabled'] = array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'Does this term appear in the enabled-only autocomplete widget?',
);
}
/*
* Implements hook_install()
*/
function term_disabler_install() {
db_add_field('taxonomy_term_data', 'enabled', array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'Does this term appear in the enabled-only autocomplete widget?',
)
);
}
/*
* Implements hook_uninstall()
*/
function term_disabler_uninstall() {
db_drop_field('taxonomy_term_data', 'enabled');
}
The form 'taxonomy_form_term' is altered by the hook term_disabler_form_taxonomy_form_term_alter() which adds a checkboxs and a submit callback to save the value.
/*
* Implements hook_form_FORM_ID_alter()
*/
function term_disabler_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
$form['term-enabled'] = array(
'#type' => 'checkbox',
'#title' => t('Enabled'),
'#weight' => -1,
'#default_value' => $form['#term']['enabled'],
);
$form['#submit'][] = '_term_disabler_taxonomy_form_term_submit';
}
/*
* Submit handler saves the checkbox state with the term entity
*/
function _term_disabler_taxonomy_form_term_submit(&$form, &$form_state) {
$tid = $form['#term']['tid'];
$enabled = $form_state['values']['term-enabled'];
$query = db_update('taxonomy_term_data')
->condition('tid', $tid)
->fields(array('enabled' => $enabled))
->execute();
drupal_set_message($query . ' rows updated');
}
A custom widget with the same form and validate callbacks as taxonomy autocomplete has a different 'autocomplete_path' pointing to a new URL. The page callback at the new URL is identical to taxonomy/autocomplete with the addition of one line when the query is being built:
$query->condition('t.enabled', 1);