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

h_razack created an issue. See original summary.

nolfranklin’s picture

Having the same problem. Thanks for the ".value" quick fix, @h_razack.

anonymous_mouse’s picture

jmuzz’s picture

See the related issue for information about displaying images / files.

jmuzz’s picture

Title: How to access fields from twig? » Allow access to subfields from twig

The 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.

jmuzz’s picture

Category: Support request » Feature request
jmuzz’s picture

Status: Active » Needs review
StatusFileSize
new1.77 KB

This should work as long as the formatter is "Field Collection Items" or "Editable Field Collection Items"

For example, in field--field-collection.html.twig:

{{ items[0].content.field_aaa }}

Will display the subfield "field_aaa" properly rendered and formatted, labels and all.

  • jmuzz committed dcc8acf on 8.x-1.x
    Issue #2628648 by jmuzz: Allow access to subfields from twig
    
jmuzz’s picture

Status: Needs review » Fixed

No news is good news I'm sure.

If there are any further problems with this please open a new issue.

icicleking’s picture

The 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!

jmuzz’s picture

I probably should have said: This patch is committed now and included in the latest dev.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.