Q:

Is it safe to call field_view_field() for a field that isn't attached to the given node?

My page.tpl.php includes:
if ($node) {
    // field_suburb is a "text" field that doesn't exist on this node type
    $f = field_view_field('node', $node, 'field_suburb');
    print render($f);
}

This triggers:

PHP Fatal error: Cannot access empty property in field/field.attach.inc

I added the following debug code in field.attach.inc ("if field name is null" block):
foreach ($languages as $langcode) {
    if ($field_name === null) {
        print $field_name === null ? "FIELD NAME IS NULL\n" : '';
        print $instance == null ? "INSTANCE IS NULL\n" : '';
        print "$entity_type $bundle\n";
        print_r($instances);
        print_r($options);
    }
    $grouped_items[$field_id][$langcode][$id] = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
    // Group the instances and entities corresponding to the current field
    $grouped_instances[$field_id][$langcode][$id] = $instance;
    $grouped_entities[$field_id][$langcode][$id] = $entities[$id];
}

That code prints:
FIELD NAME IS NULL
INSTANCE IS NULL
ENTITY TYPE: node BUNDLE: news
Array
(
    [0] => 
)
Array
(
    [field_name] => field_suburb
    [language] => 
    [default] => 1
    [deleted] => 
)

This is easy enough to protect against - I can just check my node type before accessing the field - but surely field_view_field should just return null for a field that doesn't exist instead of having the entire site die?!?
Should it be safe to call field_view_field() - i.e. is this a bug? If it's not a bug, then what's the easiest way to check to see if my given node content type actually has the field I'm rendering? Checking the type against a list of known safe types isn't very flexible, and calling field_get_items() followed by field_view_value() seems redundant when field_view_field() is available.
Drupal version is 7.22.

A:

Source code of this function looks as follows:
function field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL) {
  $output = array();

  if ($field = field_info_field($field_name)) {
  // Actual work on field, not needed here in this answer
  }

  return $output;
}

It means that if there is no field, empty array will be returned. That's all. Is it safe? Depends what are you doing with that array down the road. For example you cannot render empty arrays with render(), as it accepts only arrays representing Drupal's renderable elements.
Note that this is from the current, 7.23 version of Drupal.

