4

I'm using field_info_instances($entity,$bundle) to read through every field in a given content type in their weighted order. However, field_info_instances does not include the node title. Why not and how can I remedy it so its added to the $fields array for sorting and processing in this scenario:

<?php 
function do_something($content_type){
    $fields = field_info_instances("node",$content_type);
    usort($fields,"sort_stuff");
    foreach($fields as $field_name=>$value){
        do_something($value);
    }
}

function sort_stuff($a,$b){
    return $a['widget']['weight']-$b['widget']['weight'];
}
?>
9

The node title is not a field handled from the field API. If you want to know if a content type has a title, you can use the following code.

$types = node_type_get_types();

if (isset($types[$content_type]) && $types[$content_type]->has_title) {
  $title = $types[$content_type]->title_label;
}

The code you are looking for is the same code used by Drupal to sort the fields (and extra fields) in admin/structure/types/manage/article/fields.

screenshot

The function that handles that page is field_ui_field_overview_form().

Basing on the code of that function, I wrote the code you would need to get the list of fields, and extra fields, with their label, and weight.

  $fields = array();
  $instances = field_info_instances('node', $content_type);
  $extra_fields = field_info_extra_fields('node', $content_type, 'form');

  // Fields.
  foreach ($instances as $name => $instance) {
    $field = field_info_field($instance['field_name']);
    $fields[$instance['field_name']] = array(
      'title' => $instance['label'],
      'weight' => $instance['widget']['weight'],
    );
  }

  // Non-field elements.
  foreach ($extra_fields as $name => $extra_field) {
    $fields[$name] = array(
      'title' => $extra_field['label'],
      'weight' => $extra_field['weight'],
    );
  }

Notice that the extra fields don't contain just the title, but every extra field for which a module returned information in hook_field_extra_fields(). There are modules that add fields to the node editing form, and implement hook_field_extra_fields() to allow the users with the right permission to decide the order in which their fields appear. For example, if you have installed the Mollom module, the page I shown in the previous screenshot becomes the following one.

screenshot

Notice also that it is easy to notice which fields are not implemented using the field API if you look at admin/structure/types/manage/article/fields: For those fields, the Field column doesn't contain a link. That is what happens for the fields labelled Title, and Mollom.

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.