Skip to content

Instantly share code, notes, and snippets.

@davereid
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davereid/ac99be4ca31a48720615 to your computer and use it in GitHub Desktop.
Save davereid/ac99be4ca31a48720615 to your computer and use it in GitHub Desktop.

Problem:

  • I want to render an entity using an entity_reference field formatter. This entity is independent and not a field value, so it doesn't have any parent. I want to give the end user the options of formatters to pick from and be able to fill in options.
  • If it helps think of it as you have a file entity and you want to render it using the file_generic formatter.

Context:

  • Rendering an entity embedded in filtered text (hence rendering is done in Filter plugins).
<?php
// Render a file using the 'Generic file' formatter (a nice link with an icon):
$file = file_load(1);
$field = array('type' => 'file');
// File fields are stupid with their field values.
$items = array(0 => array('fid' => $file->fid) + (array) $file);
$display = array('type' => 'file_default');
$output = field_items_render($field, array(), $items, $display);
return drupal_render($output);
function field_items_render(array $field, array $instance, array $items, array $display, $langcode = LANGUAGE_NONE) {
$field += field_info_field_types($field['type']);
$display += field_info_formatter_types($display['type']);
$instance += array(
'entity_type' => 'node',
'bundle' => '_fake',
'settings' => array(),
);
$instance['settings'] += $field['instance_settings'];
$entity_type = 'node';
$entity = NULL;
$entities = array(0 => $entity);
$entity_items = array(0 => &$items);
// Run hook_field_prepare_view() on the field module.
$function = $field['module'] . '_field_prepare_view';
if (function_exists($function)) {
$function($entity_type, $entities, $field, $instances, $langcode, $entity_items);
}
// Run hook_field_formatter_prepare_view() on the formatter module.
$function = $display['module'] . '_field_formatter_prepare_view';
if (function_exists($function)) {
$function($entity_type, $entities, $field, array(0 => $instance), $langcode, $entity_items, array(0 => $display));
}
// Run hook_field_formatter_View() on the formatter module.
$function = $display['module'] . '_field_formatter_view';
$result = $function($entity_type, NULL, $field, $instance, $langcode, $items, $display);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment