| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406 |
- <!--
- Formulaire générique
- Assure la validation des données, les actions de base (enregistrement, annulation, ...), et la confirmation avant
- de quitter si des données ont été modifiées.
- @see https://vuetifyjs.com/en/components/forms/#usage
- -->
- <template>
- <main>
- <v-form
- ref="form"
- lazy-validation
- :readonly="readonly"
- @submit.prevent=""
- @update:entity="onFormChange"
- >
- <!-- Top action bar -->
- <v-container
- v-if="actionPosition === 'both' || actionPosition === 'top'"
- :fluid="true"
- class="container btnActions"
- >
- <v-row>
- <v-col cols="12" sm="12">
- <slot name="form.button"/>
- <UiButtonSubmit
- v-if="!readonly"
- @submit="submit"
- :actions="actions"
- :validation-pending="validationPending || !isValid"
- ></UiButtonSubmit>
- </v-col>
- </v-row>
- </v-container>
- <!-- Content -->
- <slot v-bind="{model, entity}"/>
- <!-- Bottom action bar -->
- <v-container
- v-if="actionPosition === 'both' || actionPosition === 'bottom'"
- :fluid="true"
- class="container btnActions mt-6"
- >
- <v-row>
- <v-col cols="12" sm="12">
- <slot name="form.button"/>
- <UiButtonSubmit
- @submit="submit"
- :actions="actions"
- :validation-pending="validationPending || !isValid"
- ></UiButtonSubmit>
- </v-col>
- </v-row>
- </v-container>
- </v-form>
- <!-- Confirmation dialog -->
- <LazyLayoutDialog
- :show="isConfirmationDialogShowing"
- >
- <template #dialogText>
- <v-card-title class="text-h5 theme-neutral">
- {{ $t('caution') }}
- </v-card-title>
- <v-card-text>
- <br>
- <p>{{ $t('quit_without_saving_warning') }}</p>
- </v-card-text>
- </template>
- <template #dialogBtn>
- <v-btn class="mr-4 submitBtn theme-primary" @click="closeConfirmationDialog">
- {{ $t('back_to_form') }}
- </v-btn>
- <v-btn class="mr-4 submitBtn theme-primary" @click="saveAndQuit">
- {{ $t('save_and_quit') }}
- </v-btn>
- <v-btn class="mr-4 submitBtn theme-danger" @click="quitForm">
- {{ $t('quit_form') }}
- </v-btn>
- </template>
- </LazyLayoutDialog>
- </main>
- </template>
- <script setup lang="ts">
- import {computed, ComputedRef, ref, Ref} from "@vue/reactivity";
- import {FORM_FUNCTION, SUBMIT_TYPE, TYPE_ALERT} from "~/types/enum/enums";
- import { useFormStore } from "~/stores/form";
- import {Route, RouteLocationRaw} from "@intlify/vue-router-bridge";
- import {useEntityManager} from "~/composables/data/useEntityManager";
- import ApiModel from "~/models/ApiModel";
- import {usePageStore} from "~/stores/page";
- import {PropType, watch} from "@vue/runtime-core";
- import {AnyJson} from "~/types/data";
- import * as _ from 'lodash-es'
- import {useRefreshProfile} from "~/composables/data/useRefreshProfile";
- const props = defineProps({
- /**
- * Classe de l'ApiModel (ex: Organization, Notification, ...)
- */
- model: {
- type: Function as any as () => typeof ApiModel,
- required: true
- },
- /**
- * Instance de l'objet
- */
- entity: {
- type: Object as () => ApiModel,
- required: true
- },
- /**
- * TODO: compléter
- */
- onChanged: {
- type: Function,
- required: false
- },
- goBackRoute: {
- type: Object as PropType<RouteLocationRaw>,
- required: false,
- default: null
- },
- /**
- * Types de soumission disponibles (enregistrer / enregistrer et quitter)
- */
- submitActions: {
- type: Object,
- required: false,
- default: () => {
- let actions: AnyJson = {}
- actions[SUBMIT_TYPE.SAVE] = {}
- return actions
- }
- },
- /**
- * La validation est en cours
- */
- validationPending: {
- type: Boolean,
- required: false,
- default: false
- },
- /**
- * Faut-il rafraichir le profil à la soumission du formulaire?
- */
- refreshProfile: {
- type: Boolean,
- required: false,
- default: false
- },
- actionPosition: {
- type: String as PropType<'top' | 'bottom' | 'both'>,
- required: false,
- default: 'both'
- }
- })
- // ### Définitions
- const i18n = useI18n()
- const router = useRouter()
- const { em } = useEntityManager()
- const { refreshProfile } = useRefreshProfile()
- // Le formulaire est-il valide
- const isValid: Ref<boolean> = ref(true)
- // Erreurs de validation
- const errors: Ref<Array<string>> = ref([])
- // Référence au component v-form
- const form: Ref = ref(null)
- // Le formulaire est-il en lecture seule
- const readonly: ComputedRef<boolean> = computed(() => {
- return useFormStore().readonly
- })
- // La fenêtre de confirmation est-elle affichée
- const isConfirmationDialogShowing: ComputedRef<boolean> = computed(() => {
- return useFormStore().showConfirmToLeave
- })
- /**
- * Ferme la fenêtre de confirmation
- */
- const closeConfirmationDialog = () => {
- useFormStore().setShowConfirmToLeave(false)
- }
- // ### Actions du formulaire
- /**
- * Soumet le formulaire
- *
- * @param next
- */
- const submit = async (next: string|null = null) => {
- if (props.validationPending) {
- return
- }
- // Valide les données
- await validate()
- if (!isValid.value) {
- usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
- return
- }
- try {
- usePageStore().loading = true
- // TODO: est-ce qu'il faut re-fetch l'entité après le persist?
- const updatedEntity = await em.persist(props.model, props.entity)
- if (props.refreshProfile) {
- await refreshProfile()
- }
- usePageStore().addAlert(TYPE_ALERT.SUCCESS, ['saveSuccess'])
- // On retire l'état 'dirty'
- setIsDirty(false)
- afterSubmissionAction(next, updatedEntity)
- } catch (error: any) {
- if (error.response.status === 422 && error.response.data['violations']) {
- // TODO: à revoir
- const violations: Array<string> = []
- let fields: AnyJson = {}
- for (const violation of error.response.data['violations']) {
- violations.push(i18n.t(violation['message']) as string)
- fields = Object.assign(fields, {[violation['propertyPath']] : violation['message']})
- }
- useFormStore().addViolation(fields)
- usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
- }
- } finally {
- usePageStore().loading = false
- }
- }
- /**
- * Enregistre et quitte
- */
- const saveAndQuit = async () => {
- await submit()
- quitForm()
- }
- /**
- * Retourne l'action à effectuer après la soumission du formulaire
- * @param action
- * @param updatedEntity
- */
- const afterSubmissionAction = (action: string | null, updatedEntity: AnyJson) => {
- if (action === null) {
- return
- }
- const actionArgs = props.submitActions[action]
- if (action === SUBMIT_TYPE.SAVE) {
- afterSaveAction(actionArgs, updatedEntity.id)
- } else if (action === SUBMIT_TYPE.SAVE_AND_BACK) {
- afterSaveAndQuitAction(actionArgs)
- }
- }
- /**
- * Après l'action Sauvegarder
- *
- * Si on était en mode édition, on reste sur cette page (on ne fait rien).
- * Si on était en mode création, on bascule sur le mode édition
- *
- * @param route
- * @param id
- */
- function afterSaveAction(route: Route, id: number){
- if (useFormStore().formFunction === FORM_FUNCTION.CREATE) {
- route.path += id
- navigateTo(route)
- }
- }
- /**
- * Après l'action Sauvegarder et Quitter
- *
- * On redirige vers la route donnée
- *
- * @param route
- */
- function afterSaveAndQuitAction(route: Route){
- navigateTo(route)
- }
- /**
- * Quitte le formulaire sans enregistrer
- */
- const quitForm = () => {
- setIsDirty(false)
- useFormStore().setShowConfirmToLeave(false)
- em.reset(props.model, props.entity.value)
- if (router) {
- // @ts-ignore
- router.push(useFormStore().goAfterLeave) // TODO: voir si on peut pas passer ça comme prop du component
- }
- }
- const actions = computed(()=>{
- return _.keys(props.submitActions)
- })
- // #### Validation et store
- /**
- * Update store when form is changed (if valid)
- */
- const onFormChange = async () => {
- await validate()
- if (isValid.value) {
- em.save(props.model, props.entity)
- setIsDirty(true)
- if (props.onChanged) {
- // Execute the custom onChange method, if defined
- // TODO: voir quelles variables passer à cette méthode custom ; d'ailleurs, vérifier aussi si cette méthode est utilisée
- props.onChanged()
- }
- }
- }
- /**
- * Utilise la méthode validate() de v-form pour valider le formulaire et mettre à jour les variables isValid et errors
- *
- * @see https://vuetifyjs.com/en/api/v-form/#functions-validate
- */
- const validate = async function () {
- const validation = await form.value.validate()
- isValid.value = validation.valid
- errors.value = validation.errors
- }
- // #### Gestion de l'état dirty
- watch(props.entity, async (newEntity, oldEntity) => {
- await onFormChange()
- })
- /**
- * Handle events if the form is dirty to prevent submission
- * @param e
- */
- // TODO: voir si encore nécessaire avec le @submit.prevent
- const preventSubmit = (e: any) => {
- // Cancel the event
- e.preventDefault()
- // Chrome requires returnValue to be set
- e.returnValue = ''
- }
- /**
- * Applique ou retire l'état dirty (modifié) du formulaire
- */
- const setIsDirty = (dirty: boolean) => {
- useFormStore().setDirty(dirty)
- // If dirty, add the preventSubmit event listener
- // TODO: voir si encore nécessaire avec le @submit.prevent
- if (process.browser) {
- if (dirty) {
- window.addEventListener('beforeunload', preventSubmit)
- } else {
- window.removeEventListener('beforeunload', preventSubmit)
- }
- }
- }
- defineExpose({ validate })
- </script>
- <style scoped>
- .btnActions {
- text-align: right;
- }
- </style>
|