Form.vue 11 KB

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