3

This very popular article explains correct way to render fields: http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

According to the article, the correct way to render fields is like this:

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

But this is for rendering fields that are stored in a node. How would you use the code for fields in an entity?


More info

I am using Paragraphs module that lets you create custom bundles in the predefined "paragraph" entity.

You can 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.

3

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

$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, your entity's fields should have already been retrieved by the entity module's template_preprocess_entity() function and made available under the $content variable, so you shouldn't have to do all these steps in an overridden entity template.

  • 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 '15 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 '15 at 22:55
1

There is a function for that:

field_attach_view() I had to use it to get a renderable array from Paragraph entities (paragraphs module). Then you can render this array with the render() function ex:

$paragraphEntity = entity_load("paragraphs_item",array($paragraph['value']));
        //Per Paragraph field on the page-node get a renderable array of fields!
        $renderableParagraphBundle = field_attach_view("paragraphs_item", $paragraphEntity[$paragraph['value']], "full", $langcode = $GLOBALS['language']->language, $options = array());
        print render($renderableParagraphBundle);

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.