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