Form.vue 11 KB

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