Field Collections of Entity References in Views-Collection of common programming errors
I have been tinkering with this problem and trying to research for a few hours. I am still getting familiar with the entity API for Drupal 7, and have been trying to work with PHP but to no avail–I think I am missing something VERY obvious as a result of my tired brain over-thinking things.
I have two Content Types, CT1 and CT2. CT1 has a field that can hold multiple Field Collection values. In this Field Collection (field_coll_ct2) one of the fields (field_ct2_ref) is an Entity Reference to a node of content type CT2.
Now, when I am looking at a single node of type CT1, I want a block View that will show me all of the CT2 nodes referenced in that CT1 node’s field_coll_ct2 field collection field.
My primary approach, which has worked on non-field collection fields of the same kind of relation, is to add a contextual filter to the view on Content:NID. From there, since it is a block and URL parameter passing is out of the question (there are so many of these kinds of relations between 7-8 different content types, at different tuples per node, it is absolutely not feasible to use the URL for parameter-passing) I have it set to ‘Provide default value’ of type ‘PHP’ and ‘allow multiple values’ and here is where it gets hairy.
I need to get all of the field_ct2_ref entity references in the currently-viewed node’s field_coll_ct2 field collections. I’ve tried using:
$wrapper = entity_metadata_wrapper($entity_type, $entity);
return $wrapper->field_coll_ct2->field_ct2_ref->value();
or
$node=menu_get_object();
foreach ($node->field_coll_ct2['und'] as $record)
{
$values[]= $record['value'];
}
foreach($values as $val){
$tgts[]=$val['every'][index]['possible'];
}
return $tgts[omg];
and probably close to a hundred variations of the above trying to get it to return something that vaguely resembled an entity reference to a CT2 type node.
I can’t seem to dig deeply enough into the entity/field references to get to the field_ct2_ref[‘und’][0][‘target_id’] that has worked for all non-field collection fields with this kind of relationship. Or I get AJAX errors telling me ‘Unknown data property field_coll_ct2’ or console errors saying that every index I try to throw at these array objects (to even just get ONE of the values) is wrong.
Is there an easier way of doing this? Am I missing something simple and obvious–either in the way I’m implementing my View or the PHP itself?
For what it’s worth, I’ve been able to narrow down the view results without any contextual filter by selecting a relation to ‘Referencing Entity: field_ct2_ref’ but it shows ALL CT2 nodes referenced by ANY CT1 type node rather than the specific CT1 type node I’m looking at.
Thank you!
Originally posted 2013-11-09 21:43:02.