1

As the title say I want to get the list of fields which are referenced to particular vocabulary.

For example field1 and field2 are taxonomy reference fields and the vocabulary associated to them is vocab1, now if I pass vocab1 I should get field1 and field2 as the results.

1

The vocabulary that a term reference field is associated with is held in the data column in the field_config table. Unfortunately that's a serialised PHP array so there's no clean way to query it directly.

The Field Info API doesn't seem to have a function to query fields by type so you'll need to implement your own. The basic logic would be to grab a list of fields that have the taxonomy_term_reference type, along with their data, then loop through each to determine if it has the correct vocab assigned.

Something like...

function MYMODULE_term_reference_fields_by_vocab($vocab) {
  $args = array(':type' => 'taxonomy_term_reference');
  $data = db_query('SELECT field_name, data FROM {field_config} WHERE type = :type', $args)->fetchAllKeyed();

  $field_names = array();
  foreach ($data as $field_name => $info) {
    $info = unserialize($info);

    if ($info['settings']['allowed_values'][0]['vocabulary'] == $vocab->machine_name) {
      $field_names[] = $field_name;
    }
  }

  return $field_names;
}

You'll probably want to add a static caching mechanism to that for performance, but it'll work as-is if that's not important.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.