Form.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. const route = useRoute()
  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. const formStore = useFormStore()
  168. // Le formulaire est-il en lecture seule
  169. const readonly: ComputedRef<boolean> = computed(() => {
  170. return formStore.readonly
  171. })
  172. /**
  173. * Si l'utilisateur veut quitter le formulaire sans enregistrer ses modifications,
  174. * on affiche la fenêtre de confirmation. En attendant, on garde en mémoire la route qu'il
  175. * voulait suivre au cas où il confirmerait.
  176. */
  177. const requestedLeavingRoute: Ref<RouteLocationNormalized | null> = ref(null)
  178. // La fenêtre de confirmation est-elle affichée
  179. const isConfirmationDialogShowing: ComputedRef<boolean> = computed(() => {
  180. return formStore.showConfirmToLeave
  181. })
  182. /**
  183. * Ferme la fenêtre de confirmation
  184. */
  185. const closeConfirmationDialog = () => {
  186. requestedLeavingRoute.value = null
  187. formStore.setShowConfirmToLeave(false)
  188. }
  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. if (props.refreshProfile) {
  210. await refreshProfile()
  211. }
  212. usePageStore().addAlert(TYPE_ALERT.SUCCESS, ['saveSuccess'])
  213. // On retire l'état 'dirty'
  214. setIsDirty(false)
  215. const actionArgs = next ? props.submitActions[next] : null
  216. if (next === SUBMIT_TYPE.SAVE) {
  217. onSaveAction(actionArgs, updatedEntity.id)
  218. } else if (next === SUBMIT_TYPE.SAVE_AND_BACK) {
  219. onSaveAndQuitAction(actionArgs)
  220. }
  221. } catch (error: any) {
  222. if (
  223. error.response &&
  224. error.response.status === 422 &&
  225. error.response.data.violations
  226. ) {
  227. // TODO: à revoir
  228. const violations: Array<string> = []
  229. let fields: AnyJson = {}
  230. for (const violation of error.response.data.violations) {
  231. violations.push(i18n.t(violation.message) as string)
  232. fields = Object.assign(fields, {
  233. [violation.propertyPath]: violation.message,
  234. })
  235. }
  236. formStore.addViolation(fields)
  237. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  238. } else {
  239. throw error
  240. }
  241. } finally {
  242. usePageStore().loading = false
  243. }
  244. }
  245. /**
  246. * Enregistre et quitte
  247. */
  248. const saveAndQuit = async () => {
  249. await submit()
  250. cancel()
  251. }
  252. /**
  253. * Après l'action Sauvegarder
  254. *
  255. * Si on était en mode édition, on reste sur cette page (on ne fait rien).
  256. * Si on était en mode création, on bascule sur le mode édition
  257. *
  258. * @param route
  259. * @param id
  260. */
  261. function onSaveAction(route: Route, id: number) {
  262. if (formStore.formFunction === FORM_FUNCTION.CREATE) {
  263. route.path += id
  264. navigateTo(route)
  265. }
  266. }
  267. /**
  268. * Après l'action Sauvegarder et Quitter
  269. *
  270. * On redirige vers la route donnée
  271. *
  272. * @param route
  273. */
  274. function onSaveAndQuitAction(route: Route) {
  275. navigateTo(route)
  276. }
  277. /**
  278. * Avant de quitter le formulaire, si le formulaire a été modifié, on demande confirmation
  279. */
  280. onBeforeRouteLeave(
  281. (to: RouteLocationNormalized, from: RouteLocationNormalized) => {
  282. if (formStore.dirty === true) {
  283. requestedLeavingRoute.value = to
  284. formStore.setShowConfirmToLeave(true)
  285. return false
  286. }
  287. return true
  288. },
  289. )
  290. onMounted(() => {
  291. window.addEventListener('beforeunload', (event) => {
  292. if (formStore.dirty === true) {
  293. event.returnValue = i18n.t('quit_without_saving_warning')
  294. }
  295. })
  296. })
  297. /**
  298. * Quitte le formulaire sans enregistrer
  299. */
  300. const cancel = () => {
  301. setIsDirty(false)
  302. formStore.setShowConfirmToLeave(false)
  303. em.reset(props.model, props.entity)
  304. if (requestedLeavingRoute.value !== null) {
  305. navigateTo(requestedLeavingRoute.value)
  306. } else if (formStore.goAfterLeave !== null) {
  307. router.push(formStore.goAfterLeave) // TODO: voir si on peut pas passer ça comme prop du component
  308. }
  309. }
  310. const actions = computed(() => {
  311. return _.keys(props.submitActions)
  312. })
  313. // #### Validation et store
  314. /**
  315. * Update store when form is changed (if valid)
  316. */
  317. const onFormChange = async () => {
  318. if (isValid.value) {
  319. em.save(props.entity)
  320. setIsDirty(true)
  321. if (props.onChanged) {
  322. // Execute the custom onChange method, if defined
  323. // TODO: voir quelles variables passer à cette méthode custom ; d'ailleurs, vérifier aussi si cette méthode est utilisée
  324. props.onChanged()
  325. }
  326. }
  327. }
  328. /**
  329. * Utilise la méthode validate() de v-form pour valider le formulaire et mettre à jour les variables isValid et errors
  330. *
  331. * @see https://vuetifyjs.com/en/api/v-form/#functions-validate
  332. */
  333. const validate = async function () {
  334. const validation = await form.value.validate()
  335. isValid.value = validation.valid
  336. errors.value = validation.errors
  337. }
  338. // #### Gestion de l'état dirty
  339. watch(props.entity, async (newEntity, oldEntity) => {
  340. setIsDirty(true)
  341. })
  342. /**
  343. * Handle events if the form is dirty to prevent submission
  344. * @param e
  345. */
  346. // TODO: voir si encore nécessaire avec le @submit.prevent
  347. const preventSubmit = (e: any) => {
  348. // Cancel the event
  349. e.preventDefault()
  350. // Chrome requires returnValue to be set
  351. e.returnValue = ''
  352. }
  353. /**
  354. * Applique ou retire l'état dirty (modifié) du formulaire
  355. */
  356. const setIsDirty = (dirty: boolean) => {
  357. formStore.setDirty(dirty)
  358. }
  359. defineExpose({ validate })
  360. </script>
  361. <style scoped>
  362. .btnActions {
  363. text-align: right;
  364. }
  365. .confirmation-dlg-actions {
  366. display: flex;
  367. flex-direction: row;
  368. }
  369. .confirmation-dlg-actions .v-btn {
  370. min-width: 255px;
  371. max-width: 255px;
  372. margin: 0 8px;
  373. font-size: 13px;
  374. font-weight: 600;
  375. }
  376. @media (max-width: 960px) {
  377. .confirmation-dlg-actions {
  378. width: 100%;
  379. flex-direction: column;
  380. align-items: center;
  381. }
  382. .confirmation-dlg-actions .v-btn {
  383. min-width: 80%;
  384. max-width: 80%;
  385. margin: 6px 0 !important;
  386. }
  387. }
  388. </style>