0

After a long quest, finally I got the solution for splitting $content in Drupal 7 in node.tpl.php.

Previously i was using i was using :-

print $node->field_name['und'][0]['value'];

Which was giving a warning :-

Notice: Undefined offset: 0 in include() (line 24 of C:\xampp\htdocs\drup\sites\all\themes\myCustomTheme\node.tpl.php)

Now I am using the function below which works fine with no errors

$output= field_get_items('node', $node, 'field_name');
$output = $output[0]['safe_value'];
print $output;

Now the problem is I have more than 50 fields on the page , I don't think it would be efficient to call field_get_items('node', $node, 'field_name') function 50 times.

Whats the alternate ? OR should I strict to the field_get_items function OR should I strict to the print $node->field_name['und'][0]['value']; which I heard is not good to use in Drupal 7 as und is undefined. This though solves my problem but gives irritating warnings.

2

First off, 'und' is the value of the LANGUAGE_NONE constant, which is used for the content not associated to a particular language. Not all the fields have a value for that, and if you are trying to access it, you get a PHP warning.

For example, for taxonomy terms, the array structure could be one of the following.

  • tags

    screenshot

  • other taxonomy terms

    screenshot

If you need to get the field value that would be used for the currently used language, you can just use field_get_items(). Its code cannot be optimized, as it needs to determinate the language used for the field.

function field_get_items($entity_type, $entity, $field_name, $langcode = NULL) {
  $langcode = field_language($entity_type, $entity, $field_name, $langcode);
  return isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : FALSE;
}

Even the code for field_language() cannot be much optimized. You could avoid multiple calls to field_valid_language(), but that is the only thing you can do.

If you have your own code to decide which language should be used for the fields, you can access the field data directly, without using field_get_items().

0

You can install the EntityAPI module and use a meta-data wrapper to ease accessing Node fields. I believe it loads the object once and just references the field data when you want it.

You can also try the field_extract module.

I believe Drupal's entity_load() and default Drupal object caching makes your concern of calling field_get_items(), or the entity API or field_extract a non-issue as the node is retrieved once and then that cached node data is re-used for the lifetime of the page.

Give both a looksee; your mileage may vary.

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.