1
0
forked from ScoDoc/ScoDoc

ajout formulaire dynamique correspondant

This commit is contained in:
Arthur ZHU 2022-04-07 02:54:11 +02:00
parent 8d64bf3b87
commit 73b46b11dc
5 changed files with 145 additions and 48 deletions

View File

@ -41,6 +41,7 @@ from wtforms import (
DateField, DateField,
BooleanField, BooleanField,
FieldList, FieldList,
FormField,
) )
from wtforms.validators import ValidationError, DataRequired, Email, Optional from wtforms.validators import ValidationError, DataRequired, Email, Optional
from wtforms.widgets import ListWidget, CheckboxInput from wtforms.widgets import ListWidget, CheckboxInput
@ -219,18 +220,23 @@ class OffreModificationForm(FlaskForm):
class CorrespondantCreationForm(FlaskForm): class CorrespondantCreationForm(FlaskForm):
hidden_entreprise_id = HiddenField() nom = _build_string_field("Nom (*)", render_kw={"class": "form-control"})
nom = _build_string_field("Nom (*)") prenom = _build_string_field("Prénom (*)", render_kw={"class": "form-control"})
prenom = _build_string_field("Prénom (*)") telephone = _build_string_field(
telephone = _build_string_field("Téléphone (*)", required=False) "Téléphone (*)", required=False, render_kw={"class": "form-control"}
)
mail = StringField( mail = StringField(
"Mail (*)", "Mail (*)",
validators=[Optional(), Email(message="Adresse e-mail invalide")], validators=[Optional(), Email(message="Adresse e-mail invalide")],
render_kw={"class": "form-control"},
)
poste = _build_string_field(
"Poste", required=False, render_kw={"class": "form-control"}
)
service = _build_string_field(
"Service", required=False, render_kw={"class": "form-control"}
) )
poste = _build_string_field("Poste", required=False)
service = _build_string_field("Service", required=False)
# depts = MultiCheckboxField("Départements", validators=[Optional()], coerce=int) # depts = MultiCheckboxField("Départements", validators=[Optional()], coerce=int)
submit = SubmitField("Envoyer", render_kw=SUBMIT_MARGE)
# def __init__(self, *args, **kwargs): # def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs) # super().__init__(*args, **kwargs)
@ -244,16 +250,6 @@ class CorrespondantCreationForm(FlaskForm):
if not FlaskForm.validate(self): if not FlaskForm.validate(self):
validate = False validate = False
correspondant = EntrepriseCorrespondant.query.filter_by(
entreprise_id=self.hidden_entreprise_id.data,
nom=self.nom.data,
prenom=self.prenom.data,
).first()
if correspondant is not None:
self.nom.errors.append("Ce correspondant existe déjà (même nom et prénom)")
self.prenom.errors.append("")
validate = False
if not self.telephone.data and not self.mail.data: if not self.telephone.data and not self.mail.data:
self.telephone.errors.append( self.telephone.errors.append(
"Saisir un moyen de contact (mail ou téléphone)" "Saisir un moyen de contact (mail ou téléphone)"
@ -264,6 +260,45 @@ class CorrespondantCreationForm(FlaskForm):
return validate return validate
class CorrespondantsCreationForm(FlaskForm):
hidden_entreprise_id = HiddenField()
correspondants = FieldList(FormField(CorrespondantCreationForm), min_entries=1)
submit = SubmitField("Envoyer", render_kw=SUBMIT_MARGE)
def validate(self):
validate = True
if not FlaskForm.validate(self):
validate = False
correspondant_list = []
for entry in self.correspondants.entries:
if entry.nom.data.strip() and entry.prenom.data.strip():
if (
entry.nom.data.strip(),
entry.prenom.data.strip(),
) in correspondant_list:
entry.nom.errors.append(
"Vous avez saisi 2 fois le même nom et prenom"
)
entry.prenom.errors.append("")
validate = False
correspondant_list.append(
(entry.nom.data.strip(), entry.prenom.data.strip())
)
correspondant = EntrepriseCorrespondant.query.filter_by(
entreprise_id=self.hidden_entreprise_id.data,
nom=entry.nom.data,
prenom=entry.prenom.data,
).first()
if correspondant is not None:
entry.nom.errors.append(
"Ce correspondant existe déjà (même nom et prénom)"
)
entry.prenom.errors.append("")
validate = False
return validate
class CorrespondantModificationForm(FlaskForm): class CorrespondantModificationForm(FlaskForm):
hidden_correspondant_id = HiddenField() hidden_correspondant_id = HiddenField()
hidden_entreprise_id = HiddenField() hidden_entreprise_id = HiddenField()
@ -428,10 +463,12 @@ class EnvoiOffreForm(FlaskForm):
responsables = FieldList( responsables = FieldList(
_build_string_field( _build_string_field(
"Responsable (*)", "Responsable (*)",
render_kw={"placeholder": "Tapez le nom du responsable de formation"}, render_kw={
"placeholder": "Tapez le nom du responsable de formation",
"class": "form-control",
},
), ),
min_entries=1, min_entries=1,
max_entries=5,
) )
submit = SubmitField("Envoyer", render_kw=SUBMIT_MARGE) submit = SubmitField("Envoyer", render_kw=SUBMIT_MARGE)

View File

@ -12,6 +12,7 @@ from app.decorators import permission_required
from app.entreprises import LOGS_LEN from app.entreprises import LOGS_LEN
from app.entreprises.forms import ( from app.entreprises.forms import (
CorrespondantsCreationForm,
EntrepriseCreationForm, EntrepriseCreationForm,
EntrepriseModificationForm, EntrepriseModificationForm,
SuppressionConfirmationForm, SuppressionConfirmationForm,
@ -673,29 +674,30 @@ def add_correspondant(id):
entreprise = Entreprise.query.filter_by(id=id, visible=True).first_or_404( entreprise = Entreprise.query.filter_by(id=id, visible=True).first_or_404(
description=f"entreprise {id} inconnue" description=f"entreprise {id} inconnue"
) )
form = CorrespondantCreationForm(hidden_entreprise_id=entreprise.id) form = CorrespondantsCreationForm(hidden_entreprise_id=entreprise.id)
if form.validate_on_submit(): if form.validate_on_submit():
correspondant = EntrepriseCorrespondant( for correspondant_entry in form.correspondants.entries:
entreprise_id=entreprise.id, correspondant = EntrepriseCorrespondant(
nom=form.nom.data.strip(), entreprise_id=entreprise.id,
prenom=form.prenom.data.strip(), nom=correspondant_entry.nom.data.strip(),
telephone=form.telephone.data.strip(), prenom=correspondant_entry.prenom.data.strip(),
mail=form.mail.data.strip(), telephone=correspondant_entry.telephone.data.strip(),
poste=form.poste.data.strip(), mail=correspondant_entry.mail.data.strip(),
service=form.service.data.strip(), poste=correspondant_entry.poste.data.strip(),
) service=correspondant_entry.service.data.strip(),
log = EntrepriseLog( )
authenticated_user=current_user.user_name, log = EntrepriseLog(
object=entreprise.id, authenticated_user=current_user.user_name,
text="Création d'un correspondant", object=entreprise.id,
) text="Création d'un correspondant",
db.session.add(log) )
db.session.add(correspondant) db.session.add(log)
db.session.commit() db.session.add(correspondant)
flash("Le correspondant a été ajouté à la fiche entreprise.") db.session.commit()
flash("Le correspondant a été ajouté à la fiche entreprise.")
return redirect(url_for("entreprises.fiche_entreprise", id=entreprise.id)) return redirect(url_for("entreprises.fiche_entreprise", id=entreprise.id))
return render_template( return render_template(
"entreprises/form.html", "entreprises/ajout_correspondants.html",
title="Ajout correspondant", title="Ajout correspondant",
form=form, form=form,
) )
@ -1004,8 +1006,8 @@ def envoyer_offre(id):
offre_id=offre.id, offre_id=offre.id,
) )
db.session.add(envoi_offre) db.session.add(envoi_offre)
db.session.commit()
flash(f"L'offre a été envoyé à {responsable.get_nomplogin()}.") flash(f"L'offre a été envoyé à {responsable.get_nomplogin()}.")
db.session.commit()
return redirect(url_for("entreprises.fiche_entreprise", id=offre.entreprise_id)) return redirect(url_for("entreprises.fiche_entreprise", id=offre.entreprise_id))
return render_template( return render_template(
"entreprises/envoi_offre_form.html", "entreprises/envoi_offre_form.html",

View File

@ -15,6 +15,10 @@
} }
.form-error {
color: #a94442;
}
.nav-entreprise>ul>li>a:hover { .nav-entreprise>ul>li>a:hover {
color: red; color: red;
} }

View File

@ -0,0 +1,56 @@
{# -*- mode: jinja-html -*- #}
{% extends 'base.html' %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block styles %}
{{super()}}
{% endblock %}
{% block app_content %}
<h1>{{ title }}</h1>
<br>
<div class="row">
<div class="col-md-4">
<p>
(*) champs requis
</p>
<form method="POST" action="" novalidate>
{{ form.hidden_tag() }}
{% for subfield in form.correspondants %}
{% for subsubfield in subfield %}
{% if subsubfield.errors %}
{% for error in subsubfield.errors %}
<p class="help-block form-error">{{ error }}</p>
{% endfor %}
{% endif %}
{% endfor %}
{% endfor %}
{{ form.correspondants }}
<div style="margin-bottom: 10px;">
<button class="btn btn-default" id="add-correspondant-field">Ajouter un correspondant</button>
<input class="btn btn-default" type="submit" value="Envoyer">
</div>
</form>
</div>
</div>
<script>
window.onload = function(e) {
let addCorrespondantFieldBtn = document.getElementById('add-correspondant-field');
addCorrespondantFieldBtn.addEventListener('click', function(e){
e.preventDefault();
let allCorrepondantsFieldWrapper = document.getElementById('correspondants');
let allCorrepondantsField = allCorrepondantsFieldWrapper.getElementsByTagName('input');
let correspondantInputIds = []
let csrf_token = document.getElementById('csrf_token').value;
for(let i = 0; i < allCorrepondantsField.length; i++) {
correspondantInputIds.push(parseInt(allCorrepondantsField[i].name.split('-')[1]));
}
let newFieldName = `correspondants-${Math.max(...correspondantInputIds) + 1}`;
allCorrepondantsFieldWrapper.insertAdjacentHTML('beforeend',`
<li><label for="${newFieldName}">Correspondants-${Math.max(...correspondantInputIds) + 1}</label> <table id="${newFieldName}"><tr><th><label for="${newFieldName}-nom">Nom (*)</label></th><td><input class="form-control" id="${newFieldName}-nom" name="${newFieldName}-nom" required type="text" value=""></td></tr><tr><th><label for="${newFieldName}-prenom">Prénom (*)</label></th><td><input class="form-control" id="${newFieldName}-prenom" name="${newFieldName}-prenom" required type="text" value=""></td></tr><tr><th><label for="${newFieldName}-telephone">Téléphone (*)</label></th><td><input class="form-control" id="${newFieldName}-telephone" name="${newFieldName}-telephone" type="text" value=""></td></tr><tr><th><label for="${newFieldName}-mail">Mail (*)</label></th><td><input class="form-control" id="${newFieldName}-mail" name="${newFieldName}-mail" type="text" value=""></td></tr><tr><th><label for="${newFieldName}-poste">Poste</label></th><td><input class="form-control" id="${newFieldName}-poste" name="${newFieldName}-poste" type="text" value=""></td></tr><tr><th><label for="${newFieldName}-service">Service</label></th><td><input class="form-control" id="${newFieldName}-service" name="${newFieldName}-service" type="text" value=""></td></tr></table><input id="${newFieldName}-csrf_token" name="${newFieldName}-csrf_token" type="hidden" value=${csrf_token}></li>
`);
});
}
</script>
{% endblock %}

View File

@ -22,13 +22,15 @@
{% for subfield in form.responsables %} {% for subfield in form.responsables %}
{% if subfield.errors %} {% if subfield.errors %}
{% for error in subfield.errors %} {% for error in subfield.errors %}
<p class="help-block">{{ error }}</p> <p class="help-block form-error">{{ error }}</p>
{% endfor %} {% endfor %}
{% endif %} {% endif %}
{% endfor %} {% endfor %}
{{ form.responsables }} {{ form.responsables }}
<button class="btn btn-default" id="add-responsable-field">Ajouter un responsable</button> <div style="margin-bottom: 10px;">
<input class="btn btn-default" type="submit" value="Envoyer"> <button class="btn btn-default" id="add-responsable-field">Ajouter un responsable</button>
<input class="btn btn-default" type="submit" value="Envoyer">
</div>
</form> </form>
</div> </div>
</div> </div>
@ -48,7 +50,6 @@
let allResponsablesField = allResponsablesFieldWrapper.getElementsByTagName('input'); let allResponsablesField = allResponsablesFieldWrapper.getElementsByTagName('input');
for(let i = 0; i < allResponsablesField.length; i++) { for(let i = 0; i < allResponsablesField.length; i++) {
new bsn.AutoSuggest(allResponsablesField[i].id, responsables_options); new bsn.AutoSuggest(allResponsablesField[i].id, responsables_options);
document.getElementById(allResponsablesField[i].id).classList.add("form-control");
} }
let addResponsableFieldBtn = document.getElementById('add-responsable-field'); let addResponsableFieldBtn = document.getElementById('add-responsable-field');
@ -56,16 +57,13 @@
e.preventDefault(); e.preventDefault();
let allResponsablesFieldWrapper = document.getElementById('responsables'); let allResponsablesFieldWrapper = document.getElementById('responsables');
let allResponsablesField = allResponsablesFieldWrapper.getElementsByTagName('input'); let allResponsablesField = allResponsablesFieldWrapper.getElementsByTagName('input');
if(allResponsablesField.length > 4) {
return;
}
let responsableInputIds = [] let responsableInputIds = []
for(let i = 0; i < allResponsablesField.length; i++) { for(let i = 0; i < allResponsablesField.length; i++) {
responsableInputIds.push(parseInt(allResponsablesField[i].name.split('-')[1])); responsableInputIds.push(parseInt(allResponsablesField[i].name.split('-')[1]));
} }
let newFieldName = `responsables-${Math.max(...responsableInputIds) + 1}`; let newFieldName = `responsables-${Math.max(...responsableInputIds) + 1}`;
allResponsablesFieldWrapper.insertAdjacentHTML('beforeend',` allResponsablesFieldWrapper.insertAdjacentHTML('beforeend',`
<li><label for="${newFieldName}">Responsable</label> <input class="form-control" id="${newFieldName}" name="${newFieldName}" type="text" value="" placeholder="Tapez le nom du responsable de formation"></li> <li><label for="${newFieldName}">Responsable (*)</label> <input class="form-control" id="${newFieldName}" name="${newFieldName}" type="text" value="" placeholder="Tapez le nom du responsable de formation"></li>
`); `);
var as_r = new bsn.AutoSuggest(newFieldName, responsables_options); var as_r = new bsn.AutoSuggest(newFieldName, responsables_options);
}); });