Form.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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 { RouteLocationNormalized, RouteLocationRaw } from 'vue-router'
  84. import * as _ from 'lodash-es'
  85. import { FORM_FUNCTION, SUBMIT_TYPE, TYPE_ALERT } from '~/types/enum/enums'
  86. import { useFormStore } from '~/stores/form'
  87. import { useEntityManager } from '~/composables/data/useEntityManager'
  88. import ApiModel from '~/models/ApiModel'
  89. import { usePageStore } from '~/stores/page'
  90. import type { AnyJson } from '~/types/data'
  91. import { useRefreshProfile } from '~/composables/data/useRefreshProfile'
  92. const props = defineProps({
  93. /**
  94. * Classe de l'ApiModel (ex: Organization, Notification, ...)
  95. */
  96. model: {
  97. type: Function as any as () => typeof ApiModel,
  98. required: true,
  99. },
  100. /**
  101. * Instance de l'objet
  102. */
  103. entity: {
  104. type: Object as () => ApiModel,
  105. required: true,
  106. },
  107. /**
  108. * TODO: compléter
  109. */
  110. onChanged: {
  111. type: Function,
  112. required: false,
  113. default: null,
  114. },
  115. goBackRoute: {
  116. type: Object as PropType<RouteLocationRaw>,
  117. required: false,
  118. default: null,
  119. },
  120. /**
  121. * Types de soumission disponibles (enregistrer / enregistrer et quitter)
  122. */
  123. submitActions: {
  124. type: Object,
  125. required: false,
  126. default: () => {
  127. const actions: AnyJson = {}
  128. actions[SUBMIT_TYPE.SAVE] = {}
  129. return actions
  130. },
  131. },
  132. /**
  133. * La validation est en cours
  134. */
  135. validationPending: {
  136. type: Boolean,
  137. required: false,
  138. default: false,
  139. },
  140. /**
  141. * Faut-il rafraichir le profil à la soumission du formulaire?
  142. */
  143. refreshProfile: {
  144. type: Boolean,
  145. required: false,
  146. default: false,
  147. },
  148. actionPosition: {
  149. type: String as PropType<'top' | 'bottom' | 'both'>,
  150. required: false,
  151. default: 'both',
  152. },
  153. })
  154. // ### Définitions
  155. const i18n = useI18n()
  156. const router = useRouter()
  157. const { em } = useEntityManager()
  158. const { refreshProfile } = useRefreshProfile()
  159. const route = useRoute()
  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. // ### Actions du formulaire
  189. /**
  190. * Soumet le formulaire
  191. *
  192. * @param next
  193. */
  194. const submit = async (next: string | null = null) => {
  195. if (props.validationPending) {
  196. return
  197. }
  198. // Valide les données
  199. await validate()
  200. if (!isValid.value) {
  201. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  202. return
  203. }
  204. try {
  205. usePageStore().loading = true
  206. // TODO: est-ce qu'il faut re-fetch l'entité après le persist?
  207. const updatedEntity = await em.persist(props.model, props.entity)
  208. if (props.refreshProfile) {
  209. await refreshProfile()
  210. }
  211. usePageStore().addAlert(TYPE_ALERT.SUCCESS, ['saveSuccess'])
  212. // On retire l'état 'dirty'
  213. setIsDirty(false)
  214. const actionArgs = next ? props.submitActions[next] : null
  215. if (next === SUBMIT_TYPE.SAVE) {
  216. onSaveAction(actionArgs, updatedEntity.id)
  217. } else if (next === SUBMIT_TYPE.SAVE_AND_BACK) {
  218. onSaveAndQuitAction(actionArgs)
  219. }
  220. } catch (error: any) {
  221. if (
  222. error.response &&
  223. error.response.status === 422 &&
  224. error.response.data.violations
  225. ) {
  226. // TODO: à revoir
  227. const violations: Array<string> = []
  228. let fields: AnyJson = {}
  229. for (const violation of error.response.data.violations) {
  230. violations.push(i18n.t(violation.message) as string)
  231. fields = Object.assign(fields, {
  232. [violation.propertyPath]: violation.message,
  233. })
  234. }
  235. formStore.addViolation(fields)
  236. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  237. } else {
  238. throw error
  239. }
  240. } finally {
  241. usePageStore().loading = false
  242. }
  243. }
  244. /**
  245. * Enregistre et quitte
  246. */
  247. const saveAndQuit = async () => {
  248. await submit()
  249. cancel()
  250. }
  251. /**
  252. * Après l'action Sauvegarder
  253. *
  254. * Si on était en mode édition, on reste sur cette page (on ne fait rien).
  255. * Si on était en mode création, on bascule sur le mode édition
  256. *
  257. * @param route
  258. * @param id
  259. */
  260. function onSaveAction(route: Route, id: number) {
  261. if (formStore.formFunction === FORM_FUNCTION.CREATE) {
  262. route.path += id
  263. navigateTo(route)
  264. }
  265. }
  266. /**
  267. * Après l'action Sauvegarder et Quitter
  268. *
  269. * On redirige vers la route donnée
  270. *
  271. * @param route
  272. */
  273. function onSaveAndQuitAction(route: Route) {
  274. navigateTo(route)
  275. }
  276. /**
  277. * Avant de quitter le formulaire, si le formulaire a été modifié, on demande confirmation
  278. */
  279. onBeforeRouteLeave(
  280. (to: RouteLocationNormalized, from: RouteLocationNormalized) => {
  281. if (formStore.dirty === true) {
  282. requestedLeavingRoute.value = to
  283. formStore.setShowConfirmToLeave(true)
  284. return false
  285. }
  286. return true
  287. },
  288. )
  289. onMounted(() => {
  290. window.addEventListener('beforeunload', (event) => {
  291. if (formStore.dirty === true) {
  292. event.returnValue = i18n.t('quit_without_saving_warning')
  293. }
  294. })
  295. })
  296. /**
  297. * Quitte le formulaire sans enregistrer
  298. */
  299. const cancel = () => {
  300. setIsDirty(false)
  301. formStore.setShowConfirmToLeave(false)
  302. em.reset(props.model, props.entity)
  303. if (requestedLeavingRoute.value !== null) {
  304. navigateTo(requestedLeavingRoute.value)
  305. } else if (formStore.goAfterLeave !== null) {
  306. router.push(formStore.goAfterLeave) // TODO: voir si on peut pas passer ça comme prop du component
  307. }
  308. }
  309. const actions = computed(() => {
  310. return _.keys(props.submitActions)
  311. })
  312. // #### Validation et store
  313. /**
  314. * Update store when form is changed (if valid)
  315. */
  316. const onFormChange = async () => {
  317. if (isValid.value) {
  318. em.save(props.model, props.entity)
  319. setIsDirty(true)
  320. if (props.onChanged) {
  321. // Execute the custom onChange method, if defined
  322. // TODO: voir quelles variables passer à cette méthode custom ; d'ailleurs, vérifier aussi si cette méthode est utilisée
  323. props.onChanged()
  324. }
  325. }
  326. }
  327. /**
  328. * Utilise la méthode validate() de v-form pour valider le formulaire et mettre à jour les variables isValid et errors
  329. *
  330. * @see https://vuetifyjs.com/en/api/v-form/#functions-validate
  331. */
  332. const validate = async function () {
  333. const validation = await form.value.validate()
  334. isValid.value = validation.valid
  335. errors.value = validation.errors
  336. }
  337. // #### Gestion de l'état dirty
  338. watch(props.entity, async (newEntity, oldEntity) => {
  339. setIsDirty(true)
  340. })
  341. /**
  342. * Handle events if the form is dirty to prevent submission
  343. * @param e
  344. */
  345. // TODO: voir si encore nécessaire avec le @submit.prevent
  346. const preventSubmit = (e: any) => {
  347. // Cancel the event
  348. e.preventDefault()
  349. // Chrome requires returnValue to be set
  350. e.returnValue = ''
  351. }
  352. /**
  353. * Applique ou retire l'état dirty (modifié) du formulaire
  354. */
  355. const setIsDirty = (dirty: boolean) => {
  356. formStore.setDirty(dirty)
  357. }
  358. defineExpose({ validate })
  359. </script>
  360. <style scoped>
  361. .btnActions {
  362. text-align: right;
  363. }
  364. .confirmation-dlg-actions {
  365. display: flex;
  366. flex-direction: row;
  367. }
  368. .confirmation-dlg-actions .v-btn {
  369. min-width: 255px;
  370. max-width: 255px;
  371. margin: 0 8px;
  372. }
  373. @media (max-width: 960px) {
  374. .confirmation-dlg-actions {
  375. width: 100%;
  376. flex-direction: column;
  377. align-items: center;
  378. }
  379. .confirmation-dlg-actions .v-btn {
  380. min-width: 80%;
  381. max-width: 80%;
  382. margin: 6px 0 !important;
  383. }
  384. }
  385. </style>