Form.vue 11 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. v-model="isValid"
  11. ref="form"
  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. @submit="submit"
  27. :actions="actions"
  28. :validation-pending="validationPending || !isValid"
  29. ></UiButtonSubmit>
  30. </v-col>
  31. </v-row>
  32. </v-container>
  33. <!-- Content -->
  34. <slot v-bind="{ model, entity }" />
  35. <!-- Bottom action bar -->
  36. <v-container
  37. v-if="actionPosition === 'both' || actionPosition === 'bottom'"
  38. :fluid="true"
  39. class="container btnActions mt-6"
  40. >
  41. <v-row>
  42. <v-col cols="12" sm="12">
  43. <slot name="form.button" />
  44. <UiButtonSubmit
  45. @submit="submit"
  46. :actions="actions"
  47. :validation-pending="validationPending || !isValid"
  48. ></UiButtonSubmit>
  49. </v-col>
  50. </v-row>
  51. </v-container>
  52. </v-form>
  53. <!-- Confirmation dialog -->
  54. <LazyLayoutDialog
  55. :show="isConfirmationDialogShowing"
  56. :maxWidth="1000"
  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. <div class="confirmation-dlg-actions">
  69. <v-btn class="theme-primary" @click="closeConfirmationDialog">
  70. {{ $t('cancel') }}
  71. </v-btn>
  72. <v-btn class="theme-primary" @click="saveAndQuit">
  73. {{ $t('save_and_quit') }}
  74. </v-btn>
  75. <v-btn class="theme-danger" @click="cancel">
  76. {{ $t('quit_with_no_saving') }}
  77. </v-btn>
  78. </div>
  79. </template>
  80. </LazyLayoutDialog>
  81. </LayoutContainer>
  82. </template>
  83. <script setup lang="ts">
  84. import {computed, ref} from "@vue/reactivity";
  85. import type {ComputedRef, Ref} from "@vue/reactivity";
  86. import {FORM_FUNCTION, SUBMIT_TYPE, TYPE_ALERT} from "~/types/enum/enums";
  87. import { useFormStore } from "~/stores/form";
  88. import type {Route, RouteLocationNormalized, RouteLocationRaw} from "@intlify/vue-router-bridge";
  89. import {useEntityManager} from "~/composables/data/useEntityManager";
  90. import ApiModel from "~/models/ApiModel";
  91. import {usePageStore} from "~/stores/page";
  92. import {watch} from "@vue/runtime-core";
  93. import type {PropType} from "@vue/runtime-core";
  94. import type {AnyJson} from "~/types/data";
  95. import * as _ from 'lodash-es'
  96. import { useRefreshProfile } from '~/composables/data/useRefreshProfile'
  97. const props = defineProps({
  98. /**
  99. * Classe de l'ApiModel (ex: Organization, Notification, ...)
  100. */
  101. model: {
  102. type: Function as any as () => typeof ApiModel,
  103. required: true,
  104. },
  105. /**
  106. * Instance de l'objet
  107. */
  108. entity: {
  109. type: Object as () => ApiModel,
  110. required: true,
  111. },
  112. /**
  113. * TODO: compléter
  114. */
  115. onChanged: {
  116. type: Function,
  117. required: false,
  118. },
  119. goBackRoute: {
  120. type: Object as PropType<RouteLocationRaw>,
  121. required: false,
  122. default: null,
  123. },
  124. /**
  125. * Types de soumission disponibles (enregistrer / enregistrer et quitter)
  126. */
  127. submitActions: {
  128. type: Object,
  129. required: false,
  130. default: () => {
  131. let actions: AnyJson = {}
  132. actions[SUBMIT_TYPE.SAVE] = {}
  133. return actions
  134. },
  135. },
  136. /**
  137. * La validation est en cours
  138. */
  139. validationPending: {
  140. type: Boolean,
  141. required: false,
  142. default: false,
  143. },
  144. /**
  145. * Faut-il rafraichir le profil à la soumission du formulaire?
  146. */
  147. refreshProfile: {
  148. type: Boolean,
  149. required: false,
  150. default: false,
  151. },
  152. actionPosition: {
  153. type: String as PropType<'top' | 'bottom' | 'both'>,
  154. required: false,
  155. default: 'both',
  156. },
  157. })
  158. // ### Définitions
  159. const i18n = useI18n()
  160. const router = useRouter()
  161. const { em } = useEntityManager()
  162. const { refreshProfile } = useRefreshProfile()
  163. const route = useRoute();
  164. // Le formulaire est-il valide
  165. const isValid: Ref<boolean> = ref(true)
  166. // Erreurs de validation
  167. const errors: Ref<Array<string>> = ref([])
  168. // Référence au component v-form
  169. const form: Ref = ref(null)
  170. const formStore = useFormStore()
  171. // Le formulaire est-il en lecture seule
  172. const readonly: ComputedRef<boolean> = computed(() => {
  173. return formStore.readonly
  174. })
  175. /**
  176. * Si l'utilisateur veut quitter le formulaire sans enregistrer ses modifications,
  177. * on affiche la fenêtre de confirmation. En attendant, on garde en mémoire la route qu'il
  178. * voulait suivre au cas où il confirmerait.
  179. */
  180. const requestedLeavingRoute: Ref<RouteLocationNormalized | null> = ref(null)
  181. // La fenêtre de confirmation est-elle affichée
  182. const isConfirmationDialogShowing: ComputedRef<boolean> = computed(() => {
  183. return formStore.showConfirmToLeave
  184. })
  185. /**
  186. * Ferme la fenêtre de confirmation
  187. */
  188. const closeConfirmationDialog = () => {
  189. requestedLeavingRoute.value = null
  190. formStore.setShowConfirmToLeave(false)
  191. }
  192. // ### Actions du formulaire
  193. /**
  194. * Soumet le formulaire
  195. *
  196. * @param next
  197. */
  198. const submit = async (next: string | null = null) => {
  199. if (props.validationPending) {
  200. return
  201. }
  202. // Valide les données
  203. await validate()
  204. if (!isValid.value) {
  205. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  206. return
  207. }
  208. try {
  209. usePageStore().loading = true
  210. // TODO: est-ce qu'il faut re-fetch l'entité après le persist?
  211. const updatedEntity = await em.persist(props.model, props.entity)
  212. if (props.refreshProfile) {
  213. await refreshProfile()
  214. }
  215. usePageStore().addAlert(TYPE_ALERT.SUCCESS, ['saveSuccess'])
  216. // On retire l'état 'dirty'
  217. setIsDirty(false)
  218. const actionArgs = next ? props.submitActions[next] : null
  219. if (next === SUBMIT_TYPE.SAVE) {
  220. onSaveAction(actionArgs, updatedEntity.id)
  221. } else if (next === SUBMIT_TYPE.SAVE_AND_BACK) {
  222. onSaveAndQuitAction(actionArgs)
  223. }
  224. } catch (error: any) {
  225. if (
  226. error.response &&
  227. error.response.status === 422 &&
  228. error.response.data['violations']
  229. ) {
  230. // TODO: à revoir
  231. const violations: Array<string> = []
  232. let fields: AnyJson = {}
  233. for (const violation of error.response.data['violations']) {
  234. violations.push(i18n.t(violation['message']) as string)
  235. fields = Object.assign(fields, {
  236. [violation['propertyPath']]: violation['message'],
  237. })
  238. }
  239. formStore.addViolation(fields)
  240. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  241. } else {
  242. throw error
  243. }
  244. } finally {
  245. usePageStore().loading = false
  246. }
  247. }
  248. /**
  249. * Enregistre et quitte
  250. */
  251. const saveAndQuit = async () => {
  252. await submit()
  253. cancel()
  254. }
  255. /**
  256. * Après l'action Sauvegarder
  257. *
  258. * Si on était en mode édition, on reste sur cette page (on ne fait rien).
  259. * Si on était en mode création, on bascule sur le mode édition
  260. *
  261. * @param route
  262. * @param id
  263. */
  264. function onSaveAction(route: Route, id: number) {
  265. if (formStore.formFunction === FORM_FUNCTION.CREATE) {
  266. route.path += id
  267. navigateTo(route)
  268. }
  269. }
  270. /**
  271. * Après l'action Sauvegarder et Quitter
  272. *
  273. * On redirige vers la route donnée
  274. *
  275. * @param route
  276. */
  277. function onSaveAndQuitAction(route: Route) {
  278. navigateTo(route)
  279. }
  280. /**
  281. * Avant de quitter le formulaire, si le formulaire a été modifié, on demande confirmation
  282. */
  283. onBeforeRouteLeave((to: RouteLocationNormalized, from: RouteLocationNormalized) => {
  284. if (formStore.dirty === true) {
  285. requestedLeavingRoute.value = to
  286. formStore.setShowConfirmToLeave(true)
  287. return false
  288. }
  289. return true
  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.model, 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. }
  375. @media (max-width: 960px) {
  376. .confirmation-dlg-actions {
  377. width: 100%;
  378. flex-direction: column;
  379. align-items: center;
  380. }
  381. .confirmation-dlg-actions .v-btn {
  382. min-width: 80%;
  383. max-width: 80%;
  384. margin: 6px 0 !important;
  385. }
  386. }
  387. </style>