Properly display form errors in counter

This commit is contained in:
Antoine Bartuccio 2024-12-20 20:18:02 +01:00
parent c6e95bc345
commit 044c6835d4
3 changed files with 19 additions and 5 deletions

View File

@ -6,6 +6,7 @@ interface InitialFormData {
/* Used to refill the form when the backend raises an error */
id?: string;
quantity?: number;
errors?: string[];
}
interface CounterConfig {
@ -28,10 +29,12 @@ interface Product {
class BasketItem {
quantity: number;
product: Product;
errors: string[];
constructor(product: Product, quantity: number) {
this.quantity = quantity;
this.product = product;
this.errors = [];
}
getBonusQuantity(): number {
@ -59,6 +62,7 @@ exportToHtml("loadCounter", (config: CounterConfig) => {
for (const entry of config.formInitial) {
if (entry.id !== undefined && entry.quantity !== undefined) {
this.addToBasket(entry.id, entry.quantity);
this.basket[entry.id].errors = entry.errors ?? [];
}
}

View File

@ -72,20 +72,24 @@
<input type="submit" value="{% trans %}Go{% endtrans %}"/>
</form>
<template x-for="error in errors">
<div class="alert alert-red" x-text="error">
{% for error in form.non_form_errors() %}
<div class="alert alert-red">
{{ error }}
</div>
</template>
{% endfor %}
<p>{% trans %}Basket: {% endtrans %}</p>
<form method="post" action="" x-ref="basketForm">
{% csrf_token %}
{{ form.errors }}
{{ form.non_form_errors() }}
<div x-ref="basketManagementForm">
{{ form.management_form }}
</div>
<template x-for="(item, index) in Object.values(basket)">
<ul>
<template x-for="error in item.errors">
<div class="alert alert-red" x-text="error">
</div>
</template>
<button @click.prevent="addToBasket(item.product.id, -1)">-</button>
<span x-text="item.quantity"></span>
<button @click.prevent="addToBasket(item.product.id, 1)">+</button>
@ -188,6 +192,7 @@
{%- if f.cleaned_data["quantity"] -%}
quantity: {{ f.cleaned_data["quantity"] | tojson }},
{%- endif -%}
errors: {{ form_errors[loop.index0] | tojson }},
},
{%- endif -%}
{%- endfor -%}

View File

@ -261,6 +261,11 @@ class CounterClick(CounterTabsMixin, CanViewMixin, SingleObjectMixin, FormView):
)
kwargs["customer"] = self.customer
# To get all forms errors to the javascript, we create a list of error list
kwargs["form_errors"] = []
for field_errors in kwargs["form"].errors:
kwargs["form_errors"].append(list(field_errors.values()))
if self.object.type == "BAR":
kwargs["student_card_fragment"] = StudentCardFormView.get_template_data(
self.customer