When building a module for Drupal 7, we surely have to deal with complex field, bundles and entities.

Sometimes we need to fecth a field name from a certain bundles and Drupal 7 hasn't provided any function to easily do this.

Why do you want to fetch a field name? Most likely you wont need to fetch it programmatically if you know what is the field name, but how about if you are building modules / themes for general use? that there is no way you could know what is the field machine name that the user created later on?

You may want to try using this snippets, although it is not perfect but it will do the job.


/**
 * Helper function to grab any field type from certain bundles
 *
 * @return
 *   An array of elements containing machine_name => human name.
 *   if nothing exists will return empty array;
 */
function vt_commerce_api_get_field_type_name($field_type, $bundles) {
  // declare $fields
  $fields = &drupal_static(__FUNCTION__);

  // break early if there is no field type or bundles to search for
  if (empty($field_type) || empty($bundles)) {
    return array();
  }

  // break early if static cache hit
  if (!isset($fields[$bundles][$field_type])) {
    foreach (field_info_fields() as $key => $field) {
      if ($field['type'] == $field_type && isset($field['bundles'][$bundles])) {
        $fields[$bundles][$field_type][] = $field['field_name'];
      }
    }
  }

  return $fields;
}

You just need to invoke it by calling vt_commerce_api_get_field_type_name($field_type, $bundles).

Like for example we are looking for fieldname type image from taxonomy, you just invoke vt_commerce_api_get_field_type_name('image', 'taxonomy_term); and the function will return an array containing all the available field name of type image from taxonomy_term bundles.

Easy right?