I had a project that needed users to only be able to select specific terms. Some of these where main parents and some leafs. I could create a view that would the required subset... except that parent term that should not be selectable had to be include to make the selectable leaf display.
In order to make this work, I ended up adding hook_term_reference_tree_element_alter() to the term_reference_tree widget so my code could mark the term form elements as disabled.
Here is the api doc I did for this. Patch be attached to next comment once I have issue #.
/**
* Hook to allow the form elements of a tree to be modified by other code.
*
* @param array $element
* The checkbox/radio button element for a single term.
* @param array $context
* An array with the following keys:
* 'element' => Array of the main checkbox_tree element.
* 'term' => A taxonomy term object. $term->children should be an array of the term
* objects that are that term's children.
* 'form_state' => The form state array.
*/
function hook_term_reference_tree_element_alter( &$element, $context ) {
global $user; // Used by example below.
// Some examples of info that can be found in the context
$form_id = $context['form_state']['build_info']['form_id'];
$vocab_obj = $context['element']['#vocabulary'];
$field_name = $context['element']['#field_name'];
$term = $context['term'];
// Example of disabling some of the terms in the tree.
if ( $field_name = "field_my_tags" ) {
// Call some custom code to get user specific tags to disable.
// Returns an array of tids.
$disabled = my_module_get_disabled_tags( $user );
if ( in_array($term->tid, $disabled ) ) {
$element['#disabled'] = TRUE;
}
}
}
Comments
Comment #1
cgmonroe commentedHere's the patch that adds this hook (against the 7.x-1.x head). Includes a new api.php file for docs.
Comment #2
alvar0hurtad0The patch aplies and is very useful.
Comment #4
alex_optimComment #5
alex_optimComment #7
radubutco commentedPorted for the 8.x-1.x.