3

According to Rendering Drupal 7 fields (the right way), the correct way to render fields is with code similar to the following one.

$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

This is for rendering node fields.

I am using the Paragraphs module which lets you create custom bundles in the predefined "paragraph" entity. I could use entity.tpl.php to override the output of Paragraph module fields.

I want to print my fields that are stored in the entity, but the above code won't work because it is for nodes.

What is the code for a generic entity's field?

2 Answers 2

3

The equivalent to the sample code you posted from the article, but for an entity type other than node would be the following one.

$entities = entity_load('ENTITY_TYPE_NAME', array($YOUR_ENTITY_ID));
$entity = $entities[$YOUR_ENTITY_ID];
$field = field_get_items('ENTITY_TYPE_NAME', $entity, 'field_name');
$output = field_view_value('ENTITY_TYPE_NAME', $entity, 'field_name', $field[$delta]);

If you're doing this in a template, the entity fields should have already been retrieved by template_preprocess_entity() and made available under the $content variable, so you shouldn't have to do all these steps in an overridden entity template.

2
  • Is there any way to use $content to just print the actual value of the field, as at the moment, it prints out the mark up and label. I know that I can make extra field templates to get rid of the mark up (and remove the label from the Druapl UI), but I'd rather just access the content of the field.
    – big_smile
    Apr 2, 2015 at 9:26
  • You ought to be able to access the entity via $content['field_name']['#object'], then use that with the last 2 lines of the above sample code to extract your $output value.
    – dblue
    Apr 2, 2015 at 22:55
2

There is a function for that: field_attach_view().

I had to use it to get a renderable array from Paragraph entities. You can render this array with render().

$paragraphEntity = entity_load("paragraphs_item",array($paragraph['value']));
$renderableParagraphBundle = field_attach_view(
  "paragraphs_item",
  $paragraphEntity[$paragraph['value']], "full",
  $GLOBALS['language']->language,
  array()
);

print render($renderableParagraphBundle);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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