From discussion over at http://drupal.stackexchange.com/questions/115117/rendering-arbitrary-fie...
You can (it's a bit convoluted but it's possible) create a FieldItemList object for an arbitrary runtilme field definition :
$items = \Drupal::typedDataManager()->create($field_definition, 1, $field_name, $node);
But calling $items->view() on it will fail, because EntityViewDisplay::viewField() doesn't use the $item->getFieldDefinition(), but goes up to the parent entity and then fetches fields definitions for it using the EntityManager's FieldDefinitions registry.
Not sure what can be done about it, just filing it for now.
Note that it's not a regression from D7 either. field_view_field() had the same pattern of fetching field definitions from the field_info_*() registry, and thus only worked on "official" field defeintions.
| Comment | File | Size | Author |
|---|---|---|---|
| #3 | EntityDisplay_inject_definitions-2274169-1.patch | 2.67 KB | yched |
Comments
Comment #1
yched commentedtag
Comment #2
yched commentedComment #3
yched commentedPatch - docs need to be polished, and tests need to be added, but posting what I have for now.
Not fully sure what a unit test for this will look like, BTW. We're testing the interaction between EntityViewBuilder::viewField() and EntityViewDisplay::build().
Comment #5
yched commentedCan't reproduce the fail locally, but - silly me, that can't work for the case described in the OP of course.
Injecting field definitions in the EntityDisplay would be needed, but is not enough :
EntityViewDisplay::build($entity) does its job by iterating on $items = $entity->get($field_name), which doesn't work in this case.
There's currently no way (that I know of) to place an arbitrary $items object with an arbitrary definition in an $entity object.
Comment #6
swentel commentedIs this something that we eventually could get around with #1875974: Abstract 'component type' specific code out of EntityDisplay ?
Comment #7
yched commented@swentel : not really AFAICT. #1875974: Abstract 'component type' specific code out of EntityDisplay will need the ability to inject field definitions in the "Field display handler", which might a tad more difficult than what the patch here does, but ultimately the blocker here is really tied to how FieldItemList object get attached to an entity.
Comment #19
smustgrave commentedHaven't seen this issue and it's 8 years old. Can it be closed?
Comment #20
larowlanThe issue still exists but it's at best minor
I think at this point we could deem this unsupported and mark it won't fix or move it to a feature request to add support
Comment #23
mstrelan commentedGiven there have been no responses since this was triaged 3 years ago, and there has been no other activity in 11 years, I think we can close this.