Implementing the Add More Pattern
The plos_add_more pattern is a complex component that manages a dynamic list of form items.
It supports both standard form submissions and HTMX-powered partial updates for a smoother user experience.
1. Template Usage
To use the pattern in your template, you need to call the plos_add_more component and provide an item slot.
The item slot is used to render each individual item in the list.
{% component "plos_add_more"
field_name="patents"
item_label="patent"
fields='[{"field_id": "patent_number", "required": True}]'
max_items=10
htmx_url="/patterns/add-more/htmx/"
%}
{% fill "item" data="slot_data" %}
{% component "plos_text_input"
label="Patent reference or number"
name="patent_number_{{ slot_data.index }}"
field_id="patent_number_{{ slot_data.index }}"
errors=slot_data.errors
value="{{ slot_data.value|plos_dictionary_fetch:'patent_number' }}"
%}
{% endcomponent %}
{% endfill %}
{% endcomponent %}
Slot Data
The item slot receives a slot_data object with the following properties:
index: The zero-based index of the current item (as a string).is_first: A boolean indicating if this is the first item in the list.errors: A dictionary of errors for the current item.value: A dictionary of values for the current item.
2. Handling HTMX Requests
The component includes a built-in Django View to handle add and delete actions via HTMX.
You should wire this view in your urls.py:
from plos_django_components.components.patterns.add_more.add_more import AddMore
urlpatterns = [
# ...
path("patterns/add-more/htmx/", AddMore.as_view(), name="add_more_htmx"),
]
The htmx_url parameter in the component call should match this URL.
3. Initial Values and State
The component manages its state using the Django session. To provide initial values (e.g., from a database),
you can pass a list of dictionaries to the values parameter.
initial_values = [
{"patent_number": "US1234567"},
{"patent_number": "EP9876543"},
]
{% component "plos_add_more"
field_name="patents"
values=initial_values
%}
When the component is first rendered, it will populate the session with these values. Subsequent interactions (add/delete) will update the session state.
4. Retrieving Saved Data
In your main view, when the form is submitted, you can retrieve the final list of values from the session
using the get_session_key_values helper function.
from plos_django_components.components.patterns.add_more.add_more import get_session_key_values
def my_view(request):
if request.method == "POST":
session_key = get_session_key_values("patents")
saved_data = request.session.get(session_key)
# Process saved_data...
# Don't forget to clear the session afterward if needed
del request.session[session_key]
return redirect("success_url")
return render(request, "my_template.html")