How to Use Hierarchical Select Hooks in Drupal 7

Hierarchical Select differs from other modules when dealing with hooks, here's the right way to implement one.

First, each HS field implementation needs a set of functions to work. The needed functions are the following:

  • hook_hierarchical_select_children
  • hook_hierarchical_select_params
  • hook_hierarchical_select_root_level
  • hook_hierarchical_select_lineage
  • hook_hierarchical_select_valid_item
  • hook_hierarchical_select_item_get_label
  • hook_hierarchical_select_create_item
  • hook_hierarchical_select_entity_count
  • hook_hierarchical_select_implementation_info
  • hook_hierarchical_select_config_info

The code

The first thing to do is to tell hierarchical_select that your module will provide the API for the field that you want to tweak. To achieve this, you can use hook_form_FORM_ID_alter() and put that line of code in it:

$form['fieldname'][LANGUAGE_NONE]['#config']['module'] = 'my_module';

Next, insert that code into your .module file :

function mymodule_hierarchical_select_params() {
  return hs_taxonomy_hierarchical_select_params(); 
function mymodule_hierarchical_select_root_level($params, $dropbox = FALSE) {
  return hs_taxonomy_hierarchical_select_root_level($params, $dropbox); 
function mymodule_hierarchical_select_children($parent, $params, $dropbox = FALSE) {
  return hs_taxonomy_hierarchical_select_children($parent, $params, $dropbox = FALSE);
function mymodule_hierarchical_select_lineage($item, $params) {
  return hs_taxonomy_hierarchical_select_lineage($item, $params);
function mymodule_hierarchical_select_valid_item($item, $params) {
  return hs_taxonomy_hierarchical_select_valid_item($item, $params);
function mymodule_hierarchical_select_item_get_label($item, $params) {
  return hs_taxonomy_hierarchical_select_item_get_label($item, $params);
function mymodule_hierarchical_select_create_item($label, $parent, $params) {
  return hs_taxonomy_hierarchical_select_create_item($label, $parent, $params);
function mymodule_hierarchical_select_entity_count($item, $params) {
  return hs_taxonomy_hierarchical_select_entity_count($item, $params);
function mymodule_hierarchical_select_implementation_info() {
  return hs_taxonomy_hierarchical_select_implementation_info();
function mymodule_hierarchical_select_config_info() {
  return hs_taxonomy_hierarchical_select_config_info();

Now, your module provides all the API needed for the field to work. Find the hook that fits your needs, remove the call to the original function (only needed for the hooks you don't want to use), copy the code of the function from the core module and start altering it :)

Lastly, don't forget to replace "mymodule" and "fieldname" with the appropriate values!