Hi there,
How do you access a field from a field collection from within a twig template?
Let's say you've got a field collection called "field_items", which has two fields: "field_title" and "field_content".
You can print the whole thing like this:
{{ content.field_items }}
But then, how can we access just one of the fields? I would have guessed something like that, but it doesn't work:
{{ content.field_items.0.field_title }}
After much testing I manage to do something like that:
{{ content.field_items.0['#field_collection_item'].field_title.value }}
However it displays the raw field without any formatting.
Any idea how we can achieve this?
Best regards,
Hubert.
Comments
Comment #2
nolfranklin commentedHaving the same problem. Thanks for the ".value" quick fix, @h_razack.
Comment #3
anonymous_mouse commentedHi,
I am having a similar issue. When trying to theme a repeatable field collection I’m unable to return a field as an entire HTML block. For Example I have a link field and I can access it’s URI value, alt tag value, and title value which I can use to create an tag but I cannot simply return the entire tag. While this is not an issue for links it has proven itself to be an issue for image fields and formatted text field. The image field will return the target_id, alt tag, height, and width values. And I can't use the target_id to create a a URI in the TWIG file. Additionally for formatted text, "value" is returning the formatted HTML as a string so I am getting the HTML markup on the page as opposed to it rendering the properly formatted HTML.
Has anyone been able to achieve this?
Thanks!
Comment #4
jmuzz commentedSee the related issue for information about displaying images / files.
Comment #5
jmuzz commentedThe fields can not currently be accessed by twig this way. The fields are accessible from the template that generates the output for the field collection, so you could make your own version of field-collection-item.html.twig that just prints the desired field.
I do think the subfields should be accessible via twig from their host.
I think the change would need to be made in src\Plugin\Field\FieldFormatter\FieldCollectionItemsFormatter.php or possibly a preprocess function.
Comment #6
jmuzz commentedComment #7
jmuzz commentedThis should work as long as the formatter is "Field Collection Items" or "Editable Field Collection Items"
For example, in field--field-collection.html.twig:
Will display the subfield "field_aaa" properly rendered and formatted, labels and all.
Comment #9
jmuzz commentedNo news is good news I'm sure.
If there are any further problems with this please open a new issue.
Comment #10
icicleking commentedThe patch didn't apply properly for me. However codes does work and the sub-fields are accessible from the host (ie, the field collection field). Thanks!
Comment #11
jmuzz commentedI probably should have said: This patch is committed now and included in the latest dev.