<template> <div> <div class="ui teal segment"> <h4> Pièce jointe <button @click="removeAttachmentFormset(form.dataKey)" class="ui small compact right floated icon button remove-formset" type="button" > <i class="ui times icon"></i> </button> </h4> {{ form.errors }} <div class="visible-fields"> <div class="two fields"> <div class="required field"> <label :for="form.title.id_for_label">{{ form.title.label }}</label> <input type="text" required :maxlength="form.title.field.max_length" :name="form.title.html_name" :id="form.title.id_for_label" v-model="form.title.value" @change="updateStore" /> {{ form.title.errors }} </div> <div class="required field"> <label>Fichier (PDF, PNG, JPEG)</label> <label class="ui icon button" :for="'attachment_file' + attachmentForm.dataKey" > <i class="file icon"></i> <span v-if="form.attachment_file.value" class="label">{{ form.attachment_file.value }}</span> <span v-else class="label">Sélectionner un fichier ... </span> </label> <input @change="onFileChange" type="file" style="display: none" :name="form.attachment_file.html_name" :id="'attachment_file' + attachmentForm.dataKey" /> {{ form.attachment_file.errors }} </div> </div> <div class="field"> <label for="form.info.id_for_label">{{ form.info.label }}</label> <textarea name="form.info.html_name" rows="5" v-model="form.info.value" @change="updateStore" ></textarea> {{ form.info.errors }} </div> </div> </div> </div> </template> <script> export default { name: "FeatureAttachmentFormset", props: ["attachmentForm"], data() { return { fileToImport: null, form: { title: { errors: null, id_for_label: "titre", field: { max_length: 30, // todo : vérifier dans django }, html_name: "titre", label: "Titre", value: "", }, attachment_file: { errors: null, html_name: "titre", label: "Titre", value: "", }, info: { value: "", errors: null, label: "Info", }, }, }; }, watch: { attachmentForm(newValue) { this.initForm(newValue); }, }, methods: { initForm(attachmentForm) { for (let el in attachmentForm) { if (el && this.form[el]) { this.form[el].value = el === "attachment_file" ? attachmentForm[el].split("/").pop() //* keep only the file name, not the path : attachmentForm[el]; } } }, removeAttachmentFormset() { this.$store.commit( "feature/REMOVE_ATTACHMENT_FORM", this.attachmentForm.dataKey ); }, updateStore() { this.$store.commit("feature/UPDATE_ATTACHMENT_FORM", { dataKey: this.attachmentForm.dataKey, title: this.form.title.value, attachment_file: this.form.attachment_file.value, info: this.form.info.value, fileToImport: this.fileToImport, }); }, onFileChange(e) { const files = e.target.files || e.dataTransfer.files; if (!files.length) return; this.fileToImport = files[0]; //* store file to import this.form.attachment_file.value = files[0].name; //* add name to the form for display, in order to match format return from API this.updateStore(); }, }, mounted() { this.initForm(this.attachmentForm); }, }; </script>