Form.vue 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. <!--
  2. Formulaire générique
  3. Assure la validation des données, les actions de base (enregistrement, annulation, ...), et la confirmation avant
  4. de quitter si des données ont été modifiées.
  5. @see https://vuetifyjs.com/en/components/forms/#usage
  6. -->
  7. <template>
  8. <main>
  9. <v-form
  10. ref="form"
  11. lazy-validation
  12. :readonly="readonly"
  13. @submit.prevent=""
  14. @update:entity="onFormChange"
  15. >
  16. <!-- Top action bar -->
  17. <v-container
  18. v-if="actionPosition === 'both' || actionPosition === 'top'"
  19. :fluid="true"
  20. class="container btnActions"
  21. >
  22. <v-row>
  23. <v-col cols="12" sm="12">
  24. <slot name="form.button"/>
  25. <UiButtonSubmit
  26. v-if="!readonly"
  27. @submit="submit"
  28. :actions="actions"
  29. :validation-pending="validationPending || !isValid"
  30. ></UiButtonSubmit>
  31. </v-col>
  32. </v-row>
  33. </v-container>
  34. <!-- Content -->
  35. <slot v-bind="{model, entity}"/>
  36. <!-- Bottom action bar -->
  37. <v-container
  38. v-if="actionPosition === 'both' || actionPosition === 'bottom'"
  39. :fluid="true"
  40. class="container btnActions mt-6"
  41. >
  42. <v-row>
  43. <v-col cols="12" sm="12">
  44. <slot name="form.button"/>
  45. <UiButtonSubmit
  46. @submit="submit"
  47. :actions="actions"
  48. :validation-pending="validationPending || !isValid"
  49. ></UiButtonSubmit>
  50. </v-col>
  51. </v-row>
  52. </v-container>
  53. </v-form>
  54. <!-- Confirmation dialog -->
  55. <LazyLayoutDialog
  56. :show="isConfirmationDialogShowing"
  57. >
  58. <template #dialogText>
  59. <v-card-title class="text-h5 theme-neutral">
  60. {{ $t('caution') }}
  61. </v-card-title>
  62. <v-card-text>
  63. <br>
  64. <p>{{ $t('quit_without_saving_warning') }}</p>
  65. </v-card-text>
  66. </template>
  67. <template #dialogBtn>
  68. <v-btn class="mr-4 submitBtn theme-primary" @click="closeConfirmationDialog">
  69. {{ $t('back_to_form') }}
  70. </v-btn>
  71. <v-btn class="mr-4 submitBtn theme-primary" @click="saveAndQuit">
  72. {{ $t('save_and_quit') }}
  73. </v-btn>
  74. <v-btn class="mr-4 submitBtn theme-danger" @click="quitForm">
  75. {{ $t('quit_form') }}
  76. </v-btn>
  77. </template>
  78. </LazyLayoutDialog>
  79. </main>
  80. </template>
  81. <script setup lang="ts">
  82. import {computed, ref} from "@vue/reactivity";
  83. import type {ComputedRef, Ref} from "@vue/reactivity";
  84. import {FORM_FUNCTION, SUBMIT_TYPE, TYPE_ALERT} from "~/types/enum/enums";
  85. import { useFormStore } from "~/stores/form";
  86. import type {Route, RouteLocationRaw} from "@intlify/vue-router-bridge";
  87. import {useEntityManager} from "~/composables/data/useEntityManager";
  88. import ApiModel from "~/models/ApiModel";
  89. import {usePageStore} from "~/stores/page";
  90. import {watch} from "@vue/runtime-core";
  91. import type {PropType} from "@vue/runtime-core";
  92. import type {AnyJson} from "~/types/data";
  93. import * as _ from 'lodash-es'
  94. import {useRefreshProfile} from "~/composables/data/useRefreshProfile";
  95. const props = defineProps({
  96. /**
  97. * Classe de l'ApiModel (ex: Organization, Notification, ...)
  98. */
  99. model: {
  100. type: Function as any as () => typeof ApiModel,
  101. required: true
  102. },
  103. /**
  104. * Instance de l'objet
  105. */
  106. entity: {
  107. type: Object as () => ApiModel,
  108. required: true
  109. },
  110. /**
  111. * TODO: compléter
  112. */
  113. onChanged: {
  114. type: Function,
  115. required: false
  116. },
  117. goBackRoute: {
  118. type: Object as PropType<RouteLocationRaw>,
  119. required: false,
  120. default: null
  121. },
  122. /**
  123. * Types de soumission disponibles (enregistrer / enregistrer et quitter)
  124. */
  125. submitActions: {
  126. type: Object,
  127. required: false,
  128. default: () => {
  129. let actions: AnyJson = {}
  130. actions[SUBMIT_TYPE.SAVE] = {}
  131. return actions
  132. }
  133. },
  134. /**
  135. * La validation est en cours
  136. */
  137. validationPending: {
  138. type: Boolean,
  139. required: false,
  140. default: false
  141. },
  142. /**
  143. * Faut-il rafraichir le profil à la soumission du formulaire?
  144. */
  145. refreshProfile: {
  146. type: Boolean,
  147. required: false,
  148. default: false
  149. },
  150. actionPosition: {
  151. type: String as PropType<'top' | 'bottom' | 'both'>,
  152. required: false,
  153. default: 'both'
  154. }
  155. })
  156. // ### Définitions
  157. const i18n = useI18n()
  158. const router = useRouter()
  159. const { em } = useEntityManager()
  160. const { refreshProfile } = useRefreshProfile()
  161. // Le formulaire est-il valide
  162. const isValid: Ref<boolean> = ref(true)
  163. // Erreurs de validation
  164. const errors: Ref<Array<string>> = ref([])
  165. // Référence au component v-form
  166. const form: Ref = ref(null)
  167. // Le formulaire est-il en lecture seule
  168. const readonly: ComputedRef<boolean> = computed(() => {
  169. return useFormStore().readonly
  170. })
  171. // La fenêtre de confirmation est-elle affichée
  172. const isConfirmationDialogShowing: ComputedRef<boolean> = computed(() => {
  173. return useFormStore().showConfirmToLeave
  174. })
  175. /**
  176. * Ferme la fenêtre de confirmation
  177. */
  178. const closeConfirmationDialog = () => {
  179. useFormStore().setShowConfirmToLeave(false)
  180. }
  181. // ### Actions du formulaire
  182. /**
  183. * Soumet le formulaire
  184. *
  185. * @param next
  186. */
  187. const submit = async (next: string|null = null) => {
  188. if (props.validationPending) {
  189. return
  190. }
  191. // Valide les données
  192. await validate()
  193. if (!isValid.value) {
  194. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  195. return
  196. }
  197. try {
  198. usePageStore().loading = true
  199. // TODO: est-ce qu'il faut re-fetch l'entité après le persist?
  200. const updatedEntity = await em.persist(props.model, props.entity)
  201. if (props.refreshProfile) {
  202. await refreshProfile()
  203. }
  204. usePageStore().addAlert(TYPE_ALERT.SUCCESS, ['saveSuccess'])
  205. // On retire l'état 'dirty'
  206. setIsDirty(false)
  207. afterSubmissionAction(next, updatedEntity)
  208. } catch (error: any) {
  209. if (error.response.status === 422 && error.response.data['violations']) {
  210. // TODO: à revoir
  211. const violations: Array<string> = []
  212. let fields: AnyJson = {}
  213. for (const violation of error.response.data['violations']) {
  214. violations.push(i18n.t(violation['message']) as string)
  215. fields = Object.assign(fields, {[violation['propertyPath']] : violation['message']})
  216. }
  217. useFormStore().addViolation(fields)
  218. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  219. }
  220. } finally {
  221. usePageStore().loading = false
  222. }
  223. }
  224. /**
  225. * Enregistre et quitte
  226. */
  227. const saveAndQuit = async () => {
  228. await submit()
  229. quitForm()
  230. }
  231. /**
  232. * Retourne l'action à effectuer après la soumission du formulaire
  233. * @param action
  234. * @param updatedEntity
  235. */
  236. const afterSubmissionAction = (action: string | null, updatedEntity: AnyJson) => {
  237. if (action === null) {
  238. return
  239. }
  240. const actionArgs = props.submitActions[action]
  241. if (action === SUBMIT_TYPE.SAVE) {
  242. afterSaveAction(actionArgs, updatedEntity.id)
  243. } else if (action === SUBMIT_TYPE.SAVE_AND_BACK) {
  244. afterSaveAndQuitAction(actionArgs)
  245. }
  246. }
  247. /**
  248. * Après l'action Sauvegarder
  249. *
  250. * Si on était en mode édition, on reste sur cette page (on ne fait rien).
  251. * Si on était en mode création, on bascule sur le mode édition
  252. *
  253. * @param route
  254. * @param id
  255. */
  256. function afterSaveAction(route: Route, id: number){
  257. if (useFormStore().formFunction === FORM_FUNCTION.CREATE) {
  258. route.path += id
  259. navigateTo(route)
  260. }
  261. }
  262. /**
  263. * Après l'action Sauvegarder et Quitter
  264. *
  265. * On redirige vers la route donnée
  266. *
  267. * @param route
  268. */
  269. function afterSaveAndQuitAction(route: Route){
  270. navigateTo(route)
  271. }
  272. /**
  273. * Quitte le formulaire sans enregistrer
  274. */
  275. const quitForm = () => {
  276. setIsDirty(false)
  277. useFormStore().setShowConfirmToLeave(false)
  278. em.reset(props.model, props.entity.value)
  279. if (router) {
  280. // @ts-ignore
  281. router.push(useFormStore().goAfterLeave) // TODO: voir si on peut pas passer ça comme prop du component
  282. }
  283. }
  284. const actions = computed(()=>{
  285. return _.keys(props.submitActions)
  286. })
  287. // #### Validation et store
  288. /**
  289. * Update store when form is changed (if valid)
  290. */
  291. const onFormChange = async () => {
  292. await validate()
  293. if (isValid.value) {
  294. em.save(props.model, props.entity)
  295. setIsDirty(true)
  296. if (props.onChanged) {
  297. // Execute the custom onChange method, if defined
  298. // TODO: voir quelles variables passer à cette méthode custom ; d'ailleurs, vérifier aussi si cette méthode est utilisée
  299. props.onChanged()
  300. }
  301. }
  302. }
  303. /**
  304. * Utilise la méthode validate() de v-form pour valider le formulaire et mettre à jour les variables isValid et errors
  305. *
  306. * @see https://vuetifyjs.com/en/api/v-form/#functions-validate
  307. */
  308. const validate = async function () {
  309. const validation = await form.value.validate()
  310. isValid.value = validation.valid
  311. errors.value = validation.errors
  312. }
  313. // #### Gestion de l'état dirty
  314. watch(props.entity, async (newEntity, oldEntity) => {
  315. await onFormChange()
  316. })
  317. /**
  318. * Handle events if the form is dirty to prevent submission
  319. * @param e
  320. */
  321. // TODO: voir si encore nécessaire avec le @submit.prevent
  322. const preventSubmit = (e: any) => {
  323. // Cancel the event
  324. e.preventDefault()
  325. // Chrome requires returnValue to be set
  326. e.returnValue = ''
  327. }
  328. /**
  329. * Applique ou retire l'état dirty (modifié) du formulaire
  330. */
  331. const setIsDirty = (dirty: boolean) => {
  332. useFormStore().setDirty(dirty)
  333. // If dirty, add the preventSubmit event listener
  334. // TODO: voir si encore nécessaire avec le @submit.prevent
  335. if (process.browser) {
  336. if (dirty) {
  337. window.addEventListener('beforeunload', preventSubmit)
  338. } else {
  339. window.removeEventListener('beforeunload', preventSubmit)
  340. }
  341. }
  342. }
  343. defineExpose({ validate })
  344. </script>
  345. <style scoped>
  346. .btnActions {
  347. text-align: right;
  348. }
  349. </style>