2

I'm using the field collection module in Drupal 8 to encapsulate event informations so I've got a field collection with six sub fields (place, starting time, etc.).

In my twig template field--field-event.html.twig, I'd like to extract each item of the field collection and bring it separately to the view - but I can't figure it out. What's the right way to get the content of each field collection item and process it individually?

{% for item in items %}
  {{ kint(item) }}
{% endfor %}

Iterating through the field collection with above code gives me an impression that the field collection items have got a content (with #markup) and attributes but how do I get to the core/values of the field items?

3
  • I had similar 'issue' in my site. I can solve this demand by creating my own field using Field API. In my case I had to mix autocomplete (taxonomy terms), select and number fields to compound one field. Its not too hard will depend with fields you need to compound. This way you have full control of you markup and print whatever you want. I never used field-collection module, check if you have an option in module settings to render each field instead just one '#markup' element. If you have just one markup element to all sub-fields just left string manipulation to get them.
    – Vagner
    Apr 29, 2016 at 13:16
  • Ok, your approach sounds good and interesting to create an own field with sub fields using the Field API and not to use the field-collection module (which firstly seemed to me to be the most conveniently way to implement fields with sub fields). Do you've got some advices / URLs where to start best with implementing such an own field / module?
    – docfnord
    Apr 29, 2016 at 13:49
  • Sure, take a look in 'telephone' module from Drupal core. Basically you will need 3 classes, FieldItem - Store data, Widget - Configure data (when you create a field from UI), Formatter - Create a render element and displays data (here you can define some options to how to display too).
    – Vagner
    Apr 29, 2016 at 19:03

1 Answer 1

0

That is not a good idea to use kint() to collect the values somewhere in #markupkeys or other render elements. You can get the values from the field object, which is in a field collection an entity which then refers to the children fields. But if you use field collection, you should try first to use the theming, that is provided by this module. That is configure the format of the field collection in ui and then look in twig debug for the templates that are used by doing this and modify them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.