0

I have a field collection set up for fields that make up a slider, one of these fields is for the alignment of text in the slider & is hidden on output. I'm trying to get the value of this hidden field & use it to set a CSS class in the .tpl file, I've managed to do this but only in the .tpl file itself. If I understand it correctly it's best practise to get the value of this field in a preprocess function & expose it as a variable to the .tpl file, I'm unsure how to do this.

This is what I have written in the .tpl.php file, and it works, but from what I understand it's not best practise.

$key = key($items[0]["entity"]["field_collection_item"]);
$alignment = $items[0]["entity"]["field_collection_item"][$key]["field_image"]["#object"]->field_alignment["und"][0]["value"];

I'm using the Drupal module fences to modify output so the code above is in the field--fences-xl-slider.tpl.php file.

0

That could potentially break and it's pretty gnarly looking, so not the best, but I've been there!

Instead if you have the field_collection_item's ID you can do:

// I'd make a more meaningful name... like slider?
// If I understand your example, this should give you the entity Object for the field_collection_item
$entity = array_shift($items[0]["entity"]["field_collection_item"]);

$field_image_data = field_get_items('field_collection_item', $entity, 'field_image');
// I'm less sure here, it looks like the image is an entity and it has sub-fields?
// You'll probably have to dig through $image to see where the entity is kept, I'm guessing
$field_alignment_data = field_get_items('file?', $field_image_data[0]['#entity'], 'field_alignment');

// Now you should be at your field
// If safe_value exists, use that.
$alignment = $field_alignment_data[0]['value'];

This is annoying, but more legible. It's what happens when you have nested data objects, things just get kind of annoying.

The other option is you could make it a field that isn't hidden and use hide('field_alignment') in the tpl.php or template_preprocess_* function (guessing it'd be template_preprocess_entity?)

|improve this answer|||||

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.