55 lines
No EOL
2 KiB
Python
55 lines
No EOL
2 KiB
Python
class Form:
|
|
def __init__(self, fields: list[dict]):
|
|
"""
|
|
Initialise la classe Form à partir d'une liste de champs.
|
|
|
|
:param fields: Liste de dictionnaire, chaque champs est défini comme :
|
|
{
|
|
"name": "client_name",
|
|
"label": "Nom du client",
|
|
"type": "text", # ou "number", "email", "select"...
|
|
"options": ["Oui", "Non"], # facultatif, utilisé pour les champs de type "select"
|
|
}
|
|
"""
|
|
self.fields = fields
|
|
self.data = {}
|
|
|
|
def ask(self):
|
|
print("Remplissez les informations suivantes :\n")
|
|
for field in self.fields:
|
|
name = field["name"]
|
|
label = field.get("label", name.replace("_", " ").capitalize())
|
|
field_type = field.get("type", "text")
|
|
|
|
value = None
|
|
|
|
if field_type == "select":
|
|
options = field.get("options", [])
|
|
print(f"{label} :")
|
|
for i, option in enumerate(options):
|
|
print(f" {i + 1}. {option}")
|
|
while True:
|
|
choice = input(f"Votre choix (numéro) : ")
|
|
if choice.isdigit() and 1 <= int(choice) <= len(options):
|
|
value = options[int(choice) - 1]
|
|
break
|
|
print("Choix invalide. Veuillez réessayer.")
|
|
|
|
elif field_type == "number":
|
|
while True:
|
|
value = input(f"{label} : ")
|
|
if value.replace('.', '', 1).isdigit():
|
|
value = float(value) if '.' in value else int(value)
|
|
break
|
|
print("Veuillez entrer un nombre valide.")
|
|
|
|
else:
|
|
value = input(f"{label} : ")
|
|
|
|
self.data[name] = value
|
|
|
|
def get_data(self) -> dict:
|
|
"""
|
|
Retourne les données collectées sous forme de dictionnaire.
|
|
"""
|
|
return self.data |