ICT:D JSON based Multi-Link Field
JSON-Based Multi-Link Field Architecture
This document summarizes a proposed architecture for storing and managing 0…N website links per record in Drupal, using a single text field containing JSON and a modal-based custom widget.
The goal is:
- A clean edit form (one line only)
- A modal to manage multiple links
- Deterministic behavior (no handler surprises)
- Easy rendering in Views and Twig
- Reusable across all content types
1. Overview
Instead of using Drupal’s multi-value Link field (which clutters the edit form), a single text field is used to store all links in JSON format.
Each record stores its own JSON string. There is no global file.
Example JSON stored in the field:
[
{ "label": "Foo", "url": "https://foo.com" },
{ "label": "Bar", "url": "https://bar.com" }
]
2. Edit Form UX
The edit form shows only one line:
Website links: [ Manage links ]
Clicking the button opens a modal where the editor can:
- Add a link
- Edit a link
- Remove a link
- Reorder links
When the modal is saved, the JSON is written back into the field.
3. Storage Model
A single field (e.g., field_links_json) stores the JSON string.
Characteristics:
- One JSON string per record
- No shared storage
- No extra entities required
- Deterministic and simple
4. Rendering in Twig
Twig can decode and loop through the JSON:
{% set links = node.field_links_json.value|json_decode %}
<ul>
{% for link in links %}
<li><a href="{{ link.url }}">{{ link.label }}</a></li>
{% endfor %}
</ul>
5. Rendering in Views
A small custom Views field handler is used.
Responsibilities:
- Read the JSON string
- Decode it
- Render 0…N links as HTML or a render array
This keeps Views clean and avoids exposing raw JSON.
6. Reusability
This architecture works for:
- All records in a content type
- Any number of content types
- Any custom entity type
The field and widget are generic and reusable.
7. Module Complexity Estimate
Approximate code size:
- Field widget: 80–120 lines
- Modal form: 100–150 lines
- Views field handler: 60–80 lines
- Module scaffolding: 20–40 lines
Total: ~260–390 lines of code.
8. Advantages
- Clean edit form (one line only)
- Deterministic behavior
- No multi-value field clutter
- No handler switching
- Easy to render in Twig and Views
- Successor-friendly and maintainable
- Reusable across the entire system
9. Considerations
- Links are not reusable across records (by design)
- Requires a small custom module
- JSON must be validated in the modal
10. Conclusion
This JSON-based approach provides a clean, predictable, and maintainable solution for managing multiple website links per record, without cluttering the edit form or relying on Drupal’s multi-value field behavior.