Display Field Values in an Accordion In Drupal
You probably already know that Drupal offers Views Accordion to display content in jQuery Accordions. This is fine if you’re looking to display specific content in this format, like a custom content type. However, what if you’re simply looking to display field values from a node on the node’s display in an accordion? This would require the use of contextual filters and block views if you were to use Views Accordion. However, there’s a much simpler way to achieve this functionality with Field Group and Field collection.
Below is the final result:
The above image shows how the field data is displayed on a node in an accordion format.
The above image shows how the field data is stored in the node. Users have complete control over the accordion title and body.
Install and Enable The Necessary Modules
Install and enable Field Group and Field collection and their dependencies.
Create a Field Collection Field
Navigate to an existing content type and add a new field using the Field collection Field Type. In my case I am going to use the default Basic Page content type. You can also create a new custom content type if you wish.
-
Add a new field called Accordion and set the field type to Field collection
-
Under Field Settings select Hide blank items and set Number of Values to Unlimited
-
Under the Manage Display Tab, located at admin/structure/types/manage/your-content-type/display configure the following:
- Set the Label to <Hidden>
- Set the Format to Field only
-
Set the View mode: to Full content
-
Save
Configure the Field Collection Field To Display Content In An Accordion
-
Navigate to the field collection configuration page at admin/structure/field-collections and select manage fields for the field collection we just created
-
Add a Text field with the following configuration:
-
Enable Required field
-
Set Number of values to 1
-
Add a Long text field with the following configuration:
-
Set Text processing to Filtered text
-
Enable Required field
-
Set Number of values to 1
- Navigate to the Mange Display tab for the field collection at admin/structure/field-collections/field-accordion/display
- Add a new field group with the following configuration
- Label: Accordion Wrapper
- Group Name: group_accordion_wrapper
-
Format: Accordion Group
- Save
- Nest the Accordion Title and Accordion Body fields under the Accordion Wrapper group you just created.
- Use the default settings for Accordion Wrapper
-
Set the labels for Accordion Title and Accordion Body to <Hidden>
- Save
Conclusion and Next Steps
Now you can navigate to your content type that has the field collection and start adding custom accordion elements. This is different than Views Accordion because the accordion formatting happens directly on the node, rather than in a custom view that need to be configured.