Form.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 (error.response && error.response.status === 422 && error.response.data['violations']) {
  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, {[violation['propertyPath']] : violation['message']})
  232. }
  233. formStore.addViolation(fields)
  234. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  235. } else {
  236. throw error
  237. }
  238. } finally {
  239. usePageStore().loading = false
  240. }
  241. }
  242. /**
  243. * Enregistre et quitte
  244. */
  245. const saveAndQuit = async () => {
  246. await submit()
  247. cancel()
  248. }
  249. /**
  250. * Après l'action Sauvegarder
  251. *
  252. * Si on était en mode édition, on reste sur cette page (on ne fait rien).
  253. * Si on était en mode création, on bascule sur le mode édition
  254. *
  255. * @param route
  256. * @param id
  257. */
  258. function onSaveAction(route: Route, id: number){
  259. if (formStore.formFunction === FORM_FUNCTION.CREATE) {
  260. route.path += id
  261. navigateTo(route)
  262. }
  263. }
  264. /**
  265. * Après l'action Sauvegarder et Quitter
  266. *
  267. * On redirige vers la route donnée
  268. *
  269. * @param route
  270. */
  271. function onSaveAndQuitAction(route: Route) {
  272. navigateTo(route)
  273. }
  274. /**
  275. * Avant de quitter le formulaire, si le formulaire a été modifié, on demande confirmation
  276. */
  277. onBeforeRouteLeave((to: RouteLocationNormalized, from: RouteLocationNormalized) => {
  278. if (formStore.dirty === true) {
  279. requestedLeavingRoute.value = to
  280. formStore.setShowConfirmToLeave(true)
  281. return false
  282. }
  283. return true
  284. });
  285. onMounted(() => {
  286. window.addEventListener('beforeunload', (event) => {
  287. if (formStore.dirty === true) {
  288. event.returnValue = i18n.t('quit_without_saving_warning')
  289. }
  290. })
  291. })
  292. /**
  293. * Quitte le formulaire sans enregistrer
  294. */
  295. const cancel = () => {
  296. setIsDirty(false)
  297. formStore.setShowConfirmToLeave(false)
  298. em.reset(props.model, props.entity)
  299. if (requestedLeavingRoute.value !== null) {
  300. navigateTo(requestedLeavingRoute.value)
  301. } else if (formStore.goAfterLeave !== null) {
  302. router.push(formStore.goAfterLeave) // TODO: voir si on peut pas passer ça comme prop du component
  303. }
  304. }
  305. const actions = computed(()=>{
  306. return _.keys(props.submitActions)
  307. })
  308. // #### Validation et store
  309. /**
  310. * Update store when form is changed (if valid)
  311. */
  312. const onFormChange = async () => {
  313. if (isValid.value) {
  314. em.save(props.model, props.entity)
  315. setIsDirty(true)
  316. if (props.onChanged) {
  317. // Execute the custom onChange method, if defined
  318. // TODO: voir quelles variables passer à cette méthode custom ; d'ailleurs, vérifier aussi si cette méthode est utilisée
  319. props.onChanged()
  320. }
  321. }
  322. }
  323. /**
  324. * Utilise la méthode validate() de v-form pour valider le formulaire et mettre à jour les variables isValid et errors
  325. *
  326. * @see https://vuetifyjs.com/en/api/v-form/#functions-validate
  327. */
  328. const validate = async function () {
  329. const validation = await form.value.validate()
  330. isValid.value = validation.valid
  331. errors.value = validation.errors
  332. }
  333. // #### Gestion de l'état dirty
  334. watch(props.entity, async (newEntity, oldEntity) => {
  335. setIsDirty(true)
  336. })
  337. /**
  338. * Handle events if the form is dirty to prevent submission
  339. * @param e
  340. */
  341. // TODO: voir si encore nécessaire avec le @submit.prevent
  342. const preventSubmit = (e: any) => {
  343. // Cancel the event
  344. e.preventDefault()
  345. // Chrome requires returnValue to be set
  346. e.returnValue = ''
  347. }
  348. /**
  349. * Applique ou retire l'état dirty (modifié) du formulaire
  350. */
  351. const setIsDirty = (dirty: boolean) => {
  352. formStore.setDirty(dirty)
  353. }
  354. defineExpose({ validate })
  355. </script>
  356. <style scoped>
  357. .btnActions {
  358. text-align: right;
  359. }
  360. .confirmation-dlg-actions {
  361. display: flex;
  362. flex-direction: row;
  363. }
  364. .confirmation-dlg-actions .v-btn {
  365. min-width: 255px;
  366. max-width: 255px;
  367. margin: 0 8px;
  368. }
  369. @media (max-width: 960px) {
  370. .confirmation-dlg-actions {
  371. width: 100%;
  372. flex-direction: column;
  373. align-items: center;
  374. }
  375. .confirmation-dlg-actions .v-btn {
  376. min-width: 80%;
  377. max-width: 80%;
  378. margin: 6px 0 !important;
  379. }
  380. }
  381. </style>