Skip to content

Instantly share code, notes, and snippets.

@waako
Last active February 4, 2019 16:14
Show Gist options
  • Save waako/3d739563fdb594402a8b to your computer and use it in GitHub Desktop.
Save waako/3d739563fdb594402a8b to your computer and use it in GitHub Desktop.
Drupal Field Collection theming, based on this article: https://fourword.fourkitchens.com/article/better-way-theme-field-collections
<?php foreach($rows as $row): ?>
<h3><?php print $row['field_collection_name_title']; ?></h3>
<?php if ($row['field_collection_name_subtitle']): ?>
<?php print render($row['field_collection_name_subtitle']['safe_value']); ?>
<?php endif; ?>
<?php print render($row['field_collection_name_content']['safe_value']); ?>
<?php endforeach; ?>
/**
* Creates a simple text rows array from a field collections, to be used in a
* field_preprocess function.
*
* @param $vars
* An array of variables to pass to the theme template.
*
* @param $field_name
* The name of the field being altered.
*
* @param $field_array
* Array of fields to be turned into rows in the field collection.
*/
function rows_from_field_collection(&$variables, $field_name, $field_array) {
$variables['rows'] = array();
foreach($variables['element']['#items'] as $key => $item) {
$entity_id = $item['value'];
$entity = field_collection_item_load($entity_id);
$wrapper = entity_metadata_wrapper('field_collection_item', $entity);
$row = array();
foreach($field_array as $field){
$row[$field] = $wrapper->$field->value();
}
$variables['rows'][] = $row;
}
}
/**
* General preprocess function for field.
*/
function rackspace_preprocess_field(&$variables, $hook) {
$function = __FUNCTION__ . '__' . $variables['element']['#field_name'];
if (function_exists($function)) {
$function($variables, $hook);
}
// Field Collection theme hook suggestions
if ($variables['element']['#field_name'] == 'field_collection_name') {
$variables['theme_hook_suggestions'][] = 'field__collection_name';
$field_array = array('field_collection_name_title', 'field_collection_name_subtitle','field_collection_name_content');
rows_from_field_collection($variables, 'field_collection_name', $field_array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment